Tuesday, March 31, 2015


In last article we saw how to upload a file to the documents library using SharePoint 2013 REST service. Now we will see how to delete a file using SharePoint 2013 REST service.

Following is the REST service to delete the file:

"/_api/web/GetFileByServerRelativeUrl('/testdoc/test11.doc')"

This service needs server relative url of file as parameter. Also take care of headers section, refer below code for headers.

Following is the complete code to delete the file:

function DeleteFile()
{
var digest = ""; 
$.ajax(
{
                url: "/_api/contextinfo",
                method: "POST",
                headers: {
                                "ACCEPT": "application/json;odata=verbose",
                                "content-type": "application/json;odata=verbose"
                },
                success: function (data) {
                digest = data.d.GetContextWebInformation.FormDigestValue;
                },
                error: function (data) {                 
                }
}).done(function() {
                $.ajax(
                                {                                             
                                                url: "/_api/web/GetFileByServerRelativeUrl('/testdoc/test11.doc')",
                                                method: "POST",                                                                                            
                                                headers: {
                                                                "ACCEPT": "application/json;odata=verbose",                                                                                                                                   
                                                                "X-RequestDigest": digest,
                                                                "IF-MATCH": "*",
                                                                "X-HTTP-Method" :"DELETE"
                                                },     
                                                success: function (data) {                                            
                                                                alert("Delete successfully");                      
                                                },
                                                error: function (data) {
                                                                alert("Error occured." + data.responseText);
                                                }
                                });                          
                });         
}
</script>
</head>
<body>

<div>
                <input type="submit" onclick="DeleteFile()" value="Delete File"> </input>
</div>
</body>
</html>

Happy SharePoint coding.

Till now we have seen how to interact with files and folders in document library. In this article we will see how to upload a file to the document library using new SharePoint 2013 REST services.
With this API uploading file to the Library has become very easy. And FileReader of HTML 5 can be used to read the file in bytes.

File upload mainly has three steps: First step is to read file in bytes array using FileReader of HTML5.

Second step is to call file upload SharePoint 2013 REST API and send the file to the server.
In third step if required you can set the fields of files.
We will see all those steps in detail in this article. Lets start with exploring each steps.

1. Read file to byte array using FileReader:

FileReader is introduced in HTML 5. And is helpful to read file to array easily at client side. This is new feature and is not supported in IE9 and older browsers.

Following is the sample code to read the file. Remember, for SharePoint REST service you need to use 'readAsArrayBuffer'.

Sample code:

var fileInput = $('#uploadFile');
var fileName = fileInput[0].files[0].name;
var reader = new FileReader();
reader.onload = function (e) {
var fileData = e.target.result;                          
};
reader.readAsArrayBuffer(fileInput[0].files[0]);


2. Upload file using REST service:

Now we have byte array ready with the help of above step. Now lets send this File to the library using REST service.
Following is the REST service to upload the file:

Parameters required for REST service: folder path where you need to upload file, file name, overwrite true or false - if you want to overwrite existing one then keep the value 'true', also send file byte array as 'data' parameter.

Following is the sample code to upload a file:

$.ajax({
              url: "/_api/web/GetFolderByServerRelativeUrl('/testdoc/folder1')/Files/add(url='" + fileName + "',overwrite=true)",
              method: "POST",
              binaryStringRequestBody: true,
              data: fileData,
              processData: false,
              headers: {
                       "ACCEPT": "application/json;odata=verbose",                                                                                                                             "X-RequestDigest": digest,
                       "content-length": fileData.byteLength
                       },                                                                                                                            
              success: function (data) {       
                                  alert("Uploaded successfully");      
                       },
               error: function (data) {
                       alert("Error occured." + data.responseText);
        });


3. Update the fields of a file:

Once file gets uploaded successfully you update the fields of files. This you can do by getting the item of uploaded file.  You can get this item by using the url which you get in the response of file upload REST service: data.d.ListItemFields.__deferred.uri.
Once you receive the item update it with the list item edit list.

Following is the complete code to upload and update the field:


<html>
<head>
<script src="/Site%20Assets/js/jquery-1.11.1.min.js"></script>
<script>

function AddFile()
{
var digest = "";

$.ajax(
{
                url: "/_api/contextinfo",
                method: "POST",
                headers: {
                                "ACCEPT": "application/json;odata=verbose",
                                "content-type": "application/json;odata=verbose"
                },
                success: function (data) {
                digest = data.d.GetContextWebInformation.FormDigestValue;
                },
                error: function (data) {
                               
                }
}).done(function() {
///////////////////////////////////////////////////////////////////////////////////////////////
                var fileInput = $('#uploadFile');
                var fileName = fileInput[0].files[0].name;
                var reader = new FileReader();
                reader.onload = function (e) {
                var fileData = e.target.result;
                                var res11 = $.ajax(
                                {
                                                //url: "/_api/web/lists/getbytitle('testdoc')/RootFolder/Files/add(url=@TargetFileName,overwrite='true')?" +
                                                //"@TargetFileName='" + fileName + "'",
                                                url: "/_api/web/GetFolderByServerRelativeUrl('/testdoc/folder1')/Files/add(url='" + fileName + "',overwrite=true)",
                                                method: "POST",
                                                binaryStringRequestBody: true,
                                                data: fileData,
                                                processData: false,
                                                headers: {
                                                                "ACCEPT": "application/json;odata=verbose",                                                                                                                                   
                                                                "X-RequestDigest": digest,
                                                                "content-length": fileData.byteLength
                                                },                                                                                                                            
                                                success: function (data) {                                            
                                                                var getItem = self.getDocumentItem(data.d.ListItemAllFields.__deferred.uri);
                                                                getItem.done(function (docItem, status, xhr) {                                                                
                                                                                var def = self.updateDocumentItem(docItem.d.__metadata,digest,fileName);
                                                                               
                                                                                $.when(def).done(function(){
                                                                                                                alert("Uploaded successfully");
                                                                                });
                                                                                                                                                                                                                                               
                                                                });                                                          
                                                },
                                                error: function (data) {
                                                                alert("Error occured." + data.responseText);
                                                }
                                });                          
                };
                reader.readAsArrayBuffer(fileInput[0].files[0]);
///////////////////////////////////////////////////////////////////////////////////////////////

});                                          
}

function getDocumentItem(fileItemUri) {           
                return jQuery.ajax({
                                url: fileItemUri,
                                type: "GET",
                                headers: {
                                "accept": "application/json;odata=verbose"
                                }
                });
}

function updateDocumentItem(docitemMetadata, digest, fileName) {
                var def = $.Deferred();
                jQuery.ajax({
                                url: docitemMetadata.uri,
                                type: "POST",
                                data: JSON.stringify({
                                                                                                '__metadata': { 'type': docitemMetadata.type }, 'Title':fileName
                                                                                }),
                                headers: {
                                                "X-RequestDigest": digest,
                                                "content-type": "application/json;odata=verbose",               
                                                "IF-MATCH": docitemMetadata.etag,
                                                "X-HTTP-Method": "MERGE"
                                },
                                success: function (data) {                                            
                                                def.resolve();
                                },
                                error: function (data) {
                                                def.resolve();
                                                alert("Error occured." + data.responseText);
                                }
                });
                return def.promise();
}
</script>
</head>
<body>
<div>
                <input id="uploadFile" type="file">
</div>

<div>
                <input type="submit" onclick="AddFile()" value="Add File"> </input>
</div>
</body>

</html>

Happy SharePoint coding.