Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have a solution that adds a custom button to the ribbon in SharePoint 2010 and am using the javascript client object model behind the scenes to copy a file from Library A to Library B when the button is pressed. The copy works fine but instead of adding the file as a new version in Library B (if the file exists there already), the file in Library B is just overwritten and the version remains at v1.0.

I have:

  • versioning turned on in Library B
  • the javascript performs a check-out of the file in Library B and then performs the copy

Is there something I'm missing? Has anybody accomplished this before? Is this not possible via the Javascript CSOM in SharePoint 2010?

Code:

var _ctx;
var _sourceFile;
var _destinationlibUrl;
var _destinationFile;

// LibraryA is the name of the 'source' Document Library
// LibraryB is the name of the 'destination' Document Library

function CopyFile() {

    // Get the current client context of the client-side object model (CSOM) runtime.
    _ctx = new SP.ClientContext.get_current();

    // Get the Web site that is associated with the client context.
    this.web = _ctx.get_web();
    _ctx.load(this.web);

    // Returns the list with the specified title from the collection.
    this.sourceList = this.web.get_lists().getByTitle('LibraryA');
    _ctx.load(this.sourceList);

    // Get the list items being selected.
    var selectedDocuments = SP.ListOperation.Selection.getSelectedItems(_ctx);
    this.currentItem = sourceList.getItemById(selectedDocuments[0].id);
    _ctx.load(this.currentItem);

    // Get the file that is represented by the item from a document library.
    _sourceFile = this.currentItem.get_file();
    _ctx.load(_sourceFile);

    _ctx.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
                           Function.createDelegate(this, this.onQueryFailed));
}

// Delegate that is called when the query completes successfully.
function onQuerySucceeded(sender, args) {
    if (_sourceFile != null) {
        _destinationlibUrl = web.get_serverRelativeUrl() +
                            '/LibraryB/' + 
                            _sourceFile.get_name();

        // Get hold of the file in the destination library.
        _destinationFile = web.getFileByServerRelativeUrl(_destinationlibUrl);
        _ctx.load(_destinationFile);

        _ctx.executeQueryAsync(Function.createDelegate(this, this.onLoadSucceeded),
                               Function.createDelegate(this, this.onQueryFailed));
    }
}

// Delegate that is called when the destination file checkout completes successfully.
function onLoadSucceeded(sender, args) {
    if (_destinationFile.get_exists() == true) {
        _destinationFile.checkOut();
    }

    _sourceFile.copyTo(_destinationlibUrl, true);
    notifyId = SP.UI.Notify.addNotification('Copying file... ' +
                                            _sourceFile.get_serverRelativeUrl() + 
                                            ' to ' + _destinationlibUrl, true);

    _ctx.executeQueryAsync(
        function (sender, args) {
            SP.UI.Notify.removeNotification(notifyId);
            SP.UI.Notify.addNotification('File copied successfully', false);

            //if (_destinationFile.get_exists() == true) {
            //_destinationFile.checkIn('Document Check-In',SP.CheckinType.majorCheckIn);
            //}

            // Redirect to Library B when complete
            window.location = web.get_serverRelativeUrl() + '/LibraryB/';
        },
        function (sender, args) {
            SP.UI.Notify.addNotification('Error copying file', false);
            SP.UI.Notify.removeNotification(notifyId);
            alert('Error occured: ' + args.get_message());
        }
    );
}

// Delegate that is called when server operation is completed with errors.
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
share|improve this question
    
Can you please post the file copying code here? Just to have the understanding how you are proceeding, may be then we could help you –  Diptarag Aug 19 '12 at 8:34

2 Answers 2

I used managed CSOM to complete the same task before. You can find the code at http://wp.me/p23FqP-1U. I am not good at JavaScript. Hopefully you can work out the JavaScript from my C# code.

Here is my C# code

public void CopySharePointDocument(string siteUrl, string srcUrl, string desinationUrl)
 {
     var relativeSrcUrl = srcUrl.Substring(srcUrl.IndexOf('/', 8));
     var relativeDestinationUrl = desinationUrl.Substring(desinationUrl.IndexOf('/', 8));
     File existFile = GetFile(siteUrl, relativeDestinationUrl);

     using (ClientContext ctx = new ClientContext(siteUrl))
     {
         ctx.Credentials = new NetworkCredential(_username, _password, _domain);
         var site = ctx.Web;
         var sourceFile = site.GetFileByServerRelativeUrl(relativeSrcUrl);
         ctx.Load(sourceFile);
         ctx.ExecuteQuery();
         if (existFile!=null)
         {
             UpdateFile(ctx, relativeSrcUrl, relativeDestinationUrl);
         }
         else
         {
             sourceFile.CopyTo(desinationUrl, false);
         }
         ctx.ExecuteQuery();
     }
 }

 static private void CopyStream(Stream source, Stream destination)
 {
     byte[] buffer = new byte[32768];
     int bytesRead;
     do
     {
         bytesRead = source.Read(buffer, 0, buffer.Length);
         destination.Write(buffer, 0, bytesRead);
     } while (bytesRead != 0);
 }

 private void UpdateFile(ClientContext ctx, string relativeSrcUrl, string relativeDestinationUrl)
 {

     FileInformation fileInformation = File.OpenBinaryDirect(ctx, relativeSrcUrl);
     using (MemoryStream memoryStream = new MemoryStream())
     {
         CopyStream(fileInformation.Stream, memoryStream);
         memoryStream.Seek(0, SeekOrigin.Begin);
         File.SaveBinaryDirect(ctx, relativeDestinationUrl, memoryStream, true);
     }
 }

 public File GetFile(string siteUrl, string relativeUrl)
 {
     using (ClientContext ctx = new ClientContext(siteUrl))
     {
         ctx.Credentials = new NetworkCredential(_username, _password, _domain);
         var site = ctx.Web;
         var file = site.GetFileByServerRelativeUrl(relativeUrl);
         try
         {
             ctx.Load(file);
             ctx.ExecuteQuery(); // this will throw exception if the file does not exist
             return file;
         }
         catch (ServerException ex)
         {
             if (ex.Message == "File Not Found.")
             {
                 return null;
             }
             throw;
         }
     }
 }
share|improve this answer
        "check it it is working for both copy and move"

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">

var _ctx;
var _sourceFile;
var _destinationlibUrl;
var _destinationFile;
var siteUrl = '/sites/intestsite';
var targetListItem;
var itemId=12;

    $(document).ready(function () {


    $("#btnCopy").on("click", function(){

    CopyFile() ;
    })
});

function CopyFile() {
    _ctx = new SP.ClientContext(siteUrl);

    // Get the Web site that is associated with the client context.
    this.web = _ctx.get_web();
    _ctx.load(this.web);

    // Returns the list with the specified title from the collection.
    this.sourceList = this.web.get_lists().getByTitle('Pages');
    _ctx.load(this.sourceList);

    // Get the list items being selected.
    //var selectedDocuments = SP.ListOperation.Selection.getSelectedItems(_ctx);
    //this.currentItem = sourceList.getItemById(selectedDocuments[0].id);

    this.currentItem = sourceList.getItemById(itemId);
    _ctx.load(this.currentItem);

    // Get the file that is represented by the item from a document library.
    _sourceFile = this.currentItem.get_file();
    _ctx.load(_sourceFile);

    _ctx.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
                           Function.createDelegate(this, this.onQueryFailed));
}

// Delegate that is called when the query completes successfully.
function onQuerySucceeded(sender, args) {


    if (_sourceFile != null) {
        _destinationlibUrl = web.get_serverRelativeUrl() +'/PageArchive/' + _sourceFile.get_name();
         alert('Now moving to: ' + _destinationlibUrl);

         //_sourceFile.moveTo(_destinationlibUrl, 1);
        _sourceFile.copyTo(_destinationlibUrl, 1);

         notifyId = SP.UI.Notify.addNotification('Moving file ' + _sourceFile.get_serverRelativeUrl() + ' to ' + _destinationlibUrl, true);


        _ctx.executeQueryAsync(
        function (sender, args) {
            SP.UI.Notify.removeNotification(notifyId);
            SP.UI.Notify.addNotification('File copied successfully', false);

            window.location = web.get_serverRelativeUrl();
        },
        function (sender, args) {
            SP.UI.Notify.addNotification('Error copying file', false);
            SP.UI.Notify.removeNotification(notifyId);
            alert('Error occured: ' + args.get_message());
        }
    );

    }

}

// Delegate that is called when the destination file checkout completes successfully.


// Delegate that is called when server operation is completed with errors.
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

</script>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.