1

I have two document libraries on the same web, and am wanting to move the files from one to the other using JSOM/CSOM.

Can anyone please shed some light on how to do this?

Thanks

5

Thanks for the help with this, though for my use case the answer was a bit more simple. Here is the code I used to move files from one document library to another (on the same web)

function moveFiles(sourceLib, destLib){

var context = new SP.ClientContext.get_current();
var web = context.get_web();
var folderSrc = web.getFolderByServerRelativeUrl(sourceLib);
context.load(folderSrc,'Files');
context.executeQueryAsync(
    function() {
        console.log("Got the source folder right here!");
        var files = folderSrc.get_files();
        var e = files.getEnumerator();
        var dest = []; //Just to check it got the file path right
        while (e.moveNext()) {
            var file = e.get_current();
            var destLibUrl = destLib + "/" + file.get_name();
            dest.push(destLibUrl); //delete this when we're happy we got the file paths right
            file.moveTo(destLibUrl, SP.MoveOperations.overwrite);
        }
        console.log(dest); //delete this when we're happy we got the file paths right
        context.executeQueryAsync(function() { console.log("Files moved successfully!");}, function(sender, args) {console.log("error: ") + args.get_message()});
        }, 
    function(sender, args){console.log("Sorry, something messed up: " + args.get_message());}
    );

}

//Usage:
var srcLibrary = 'Temp Library';
var destLibrary = 'Pages';

moveFiles(srcLibrary, destLibrary);
  • Can I get the file object after move operation(after file moved successfully)? Want to refresh some fields for this file.. – Gennady G May 29 '17 at 14:09
4

Use following code to copy documents :

public static void CopyDocuments(string srcUrl, string destUrl, string srcLibrary, string destLibrary, Login _login)
    {
        // set up the src client
        SP.ClientContext srcContext = new SP.ClientContext(srcUrl);
        srcContext.AuthenticationMode = SP.ClientAuthenticationMode.FormsAuthentication;
        srcContext.FormsAuthenticationLoginInfo = new SP.FormsAuthenticationLoginInfo(_login.UserName, _login.Password);

        // set up the destination context (in your case there is no needs to create a new context, because it would be the same library!!!!)
        SP.ClientContext destContext = new SP.ClientContext(destUrl);
        destContext.AuthenticationMode = SP.ClientAuthenticationMode.FormsAuthentication;
        destContext.FormsAuthenticationLoginInfo = new SP.FormsAuthenticationLoginInfo(_login.UserName, _login.Password);

        // get the list and items
        SP.Web srcWeb = srcContext.Web;
        SP.List srcList = srcWeb.Lists.GetByTitle(srcLibrary);
        SP.ListItemCollection col = srcList.GetItems(new SP.CamlQuery());
        srcContext.Load(col);
        srcContext.ExecuteQuery();

        // get the new list
        SP.Web destWeb = destContext.Web;
        destContext.Load(destWeb);
        destContext.ExecuteQuery();

        foreach (var doc in col)
        {
            try
            {
                if (doc.FileSystemObjectType == SP.FileSystemObjectType.File)
                {
                    // get the file
                    SP.File f = doc.File;
                    srcContext.Load(f);
                    srcContext.ExecuteQuery();

                    // build new location url
                    string nLocation = destWeb.ServerRelativeUrl.TrimEnd('/') + "/" + destLibrary.Replace(" ", "") + "/" + f.Name;

                    // read the file, copy the content to new file at new location
                    SP.FileInformation fileInfo = SP.File.OpenBinaryDirect(srcContext, f.ServerRelativeUrl);
                    SP.File.SaveBinaryDirect(destContext, nLocation, fileInfo.Stream, true);
                } 

                if (doc.FileSystemObjectType == SP.FileSystemObjectType.Folder)
                {
                    // load the folder
                    srcContext.Load(doc);
                    srcContext.ExecuteQuery();

                    // get the folder data, get the file collection in the folder
                    SP.Folder folder = srcWeb.GetFolderByServerRelativeUrl(doc.FieldValues["FileRef"].ToString());
                    SP.FileCollection fileCol = folder.Files;

                    // load everyting so we can access it
                    srcContext.Load(folder);
                    srcContext.Load(fileCol);
                    srcContext.ExecuteQuery();

                    foreach (SP.File f in fileCol)
                    {
                        // load the file
                        srcContext.Load(f);
                        srcContext.ExecuteQuery();

                        string[] parts = null;
                        string id = null;

                        if (srcLibrary == "My Files")
                        {
                            // these are doc sets
                            parts = f.ServerRelativeUrl.Split('/');
                            id = parts[parts.Length - 2];
                        }
                        else
                        {
                            id = folder.Name;
                        }

                        // build new location url
                        string nLocation = destWeb.ServerRelativeUrl.TrimEnd('/') + "/" + destLibrary.Replace(" ", "") + "/" + id + "/" + f.Name;

                        // read the file, copy the content to new file at new location
                        SP.FileInformation fileInfo = SP.File.OpenBinaryDirect(srcContext, f.ServerRelativeUrl);
                        SP.File.SaveBinaryDirect(destContext, nLocation, fileInfo.Stream, true);
                    }
                }
            }
            catch (Exception ex)
            {
                Log("File Error = " + ex.ToString());
            }
        }
    }

For jaavscript you can use SPServices JS library. Code for moving with the metadata is here: Copy document from one site to another

For more details:

http://blog.blumshapiro.com/blog/2012/08/22/sharepoint-2010-using-the-client-object-model-to-move-files-and-folders-across-site-collections-and-subsites/

  • Thanks for that, but I'm not very familiar with C# (CSOM) and also realise that there are a few methods that are not available to JSOM. Anyone generous enough to translate this into JS? Thanks – BStCroix Sep 4 '14 at 11:28
  • 2
    Updated the answer with javascript code. sharepoint.stackexchange.com/questions/91210/… – Aanchal Sep 4 '14 at 12:57
  • You should not supposed to modify the Document Library name: destLibrary.Replace(" ", "") should be destLibrary. It works now. – Jebastin J Mar 8 '18 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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