4

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()); } 
1
  • 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
    CommentedAug 19, 2012 at 8:34

3 Answers 3

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; } } } 
    2

    This works 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> 
      0

      the following code will work for copying items from one library to another library and it will also check in the file in the destination.

       function copyItem() { file=$("#filename").val(); var binary = ""; $().SPServices({ operation: "GetItem", Url: "https://<source site>/"+sourcelibname+"/"+file, completefunc: function (xData, Status) { binary = $(xData.responseXML).find("Stream").text(); $().SPServices({ operation: "CopyIntoItems", SourceUrl: "https://<source site>/"+sourcelibname+"/"+file, DestinationUrls: ["https://<source site>/<destination site>/"+destinationlibname+"/"+file], Stream: binary, completefunc: function (xData, Status) { alert(file+" has been successfully published to Technet 1."); updatemetadata(); }, error: function ajaxError(response) { alert(response.status + ' ' + response.statusText); } }); } }); } //**************************************************************************************************************** function updatemetadata() { var requestUri = "<source site>/_api/web/lists/getByTitle('"+sourcelibname+"')/items?$select=LinkFilename,*&$Filter=substringof('"+file+"',FileRef)"; var requestHeaders = { "accept": "application/json;odata=verbose" } $.ajax({ url: requestUri, type: 'GET', dataType: 'json', headers: requestHeaders, success: function (data) { metadata =data.d.results[0]; getid(); }, error: function ajaxError(response) { alert(response.status + ' ' + response.statusText); } }); } //**************************************************************************************************************** function getid() { var requestUri = "https://<source site>/<destination site>/_api/web/lists/getByTitle('"+destinationlibname+"')/items?$select=LinkFilename,*&$Filter=substringof('"+file+"',FileRef)"; var requestHeaders = { "accept": "application/json;odata=verbose" } $.ajax({ url: requestUri, type: 'GET', dataType: 'json', headers: requestHeaders, success: function (data) { updatedata(data.d.results[0].ID); }, error: function ajaxError(response) { alert(response.status + ' ' + response.statusText); } }); } //**************************************************************************************************************** function updatedata(ID) { var url = "https://<source site>/<destination site>/_api/Web/Lists/GetByTitle('"+destinationlibname+"')/Items('"+ID+"')"; var data = { __metadata: { 'type': destinationid }, 'Title':metadata.Title, }; $.ajax({ url:url, type: "POST", headers: { "Content-Type": "application/json;odata=verbose", "Accept": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val(), "X-Http-Method": "MERGE", "IF-MATCH": "*" }, data: JSON.stringify(data), success: function (data) { //alert('success'); CheckInFile(); }, error: function (error) { alert(error.responseText.split(":")[5].split("}")[0]); } }); } //**************************************************************************************************************** function CheckInFile() { var ServerRelativeUrlofFile ="https://insight.cas.com/sites/content/technet/_api/web/GetFileByServerRelativeUrl('/sites/content/technet/CASDocuments1/"+file+"')"; $.ajax ({ url: ServerRelativeUrlofFile + "/CheckIn()", type: "POST", headers: { "Accept": "application/json;odata=verbose", "Content-Type": "application/json;odata=verbose", "IF-MATCH": "*", "X-HTTP-Method": "PATCH", "X-RequestDigest": $("#__REQUESTDIGEST").val() }, success: function (data, status, xhr) { alert(file+" Published to technet successfully 2. "); }, error: function (xhr, status, error) { //alert(xhr.responseText); alert(file+" Republished to technet successfully 3. "); } }); } //**************************************************************************************************************** 

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.