1
votes

I have a question on how to change an existing file on SharePoint document library using REST API. I have a couple of files in the location http://site url/<RootFolder>/<SubFolder>/File.docx. I have a UI where it lists all the files from this subfloder location. When the user clicks on edit i am enabling the file name as textbox where the user can change the name of the file.

After doing some research i found that Constructing an endpoint that looks like this: https://<site url>/_api/web/lists/getbytitle('Documents')/items(<item id>) we can edit the file metadata properties. But i could not able to figure out the best way to update the filename of existing document that resides on SharePoint Doc library.

Could someone please help me with the REST API query to fetch the file and the approach to update the filename?

2

2 Answers

0
votes

You need to use the MoveTo Method to do this as described here in MSDN https://msdn.microsoft.com/en-us/library/office/dn450841.aspx#bk_FileMoveTo.

executor.executeAsync({
  url: "<app web url>/_api/SP.AppContextSite(@target)/web
    /getfilebyserverrelativeurl('/Shared Documents/filename.docx')
    /moveto(newurl='/Other Folder/filename.docx',flags=1)
    ?@target='<host web url>'",
  method: "POST",
  success: successHandler,
  error: errorHandler
});
1
votes

You could consider at least two options:

Option 1. Rename file name

You could update the name of the existing list item as demonstrated below

Example

function rename(webUrl,listTitle,itemId,fileName){
   var endpointUrl = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + itemId +  ")";
   return executeJson(endpointUrl)
   .then(function(data){                 
      var itemPayload = {};
      itemPayload['__metadata'] = {'type': data.d['__metadata']['type']};
      itemPayload['Title'] = fileName;
      itemPayload['FileLeafRef'] = fileName;
      var itemUrl = data.d['__metadata']['uri'];
      var headers = {};
      headers["X-HTTP-Method"] = "MERGE";
      headers["If-Match"] =  "*";
      return executeJson(itemUrl,"POST",headers,itemPayload);
   });
}

var webUrl = _spPageContextInfo.webAbsoluteUrl; // web url
var listTitle = "Documents";  //list title
var itemId = 1;  //list item id
var fileName = "SP User Guide.docx"; //new file name

rename(webUrl,listTitle,itemId,fileName)
.done(function(item){
   console.log('Renamed');
})
.fail(function(error){
    console.log(error);
});

Option 2. Move file via MoveTo REST endpoint

Example

function moveTo(webUrl,sourceFileUrl,targetFileUrl){
   var endpointUrl = webUrl + "/_api/web/getfilebyserverrelativeurl('" + sourceFileUrl + "')/moveto(newurl='" + targetFileUrl + "',flags=1)";
   return executeJson(endpointUrl,"POST");
}

var webUrl = _spPageContextInfo.webAbsoluteUrl; // web url
var sourceFileUrl = "/Documents/SP2010.docx";
var targetFileUrl = "/Documents/SP2013.docx";

moveTo(webUrl,sourceFileUrl,targetFileUrl)
.done(function(item){
   console.log('Done');
})
.fail(function(error){
    console.log(error);
});

executeJson function:

function executeJson(url,method,headers,payload) 
{
    headers = headers || {};
    method = method || 'GET';
    headers["Accept"] = "application/json;odata=verbose";
    if(method == "POST") {
        headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
    }   

    var ajaxOptions = 
    {       
       url: url,   
       type: method,  
       contentType: "application/json;odata=verbose",
       headers: headers
    };
    if(method == "POST") {
      ajaxOptions.data = JSON.stringify(payload);
    }  
    return $.ajax(ajaxOptions);
}