Upload Single/Multiple file by using the REST API and jQuery SharePoint 2013

Upload Single/Multiple file by using the REST API and jQuery SharePoint 2013

Here you can find how to upload single/multiple file in SharePoint 2013 Library using Rest API. We can use the Content Editor web part to call the script files.


Include Script files in Content Editor:

Go to content editor -> Edit Source -> enter the code like below (code for including the script files)

For 'jquery.min.js' we can either use direct link from online or we can download to our SharePoint library & We can use that.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> OR use the below code

<script src="/sites/<SiteName>/<Subsite>/SiteAssets/jquery-1.11.1.min.js"></script>
<script src="/sites/<SiteName>/<Subsite>/SiteAssets/taskpage.js" type="text/javascript"></script>
<script src="/sites/<SiteName>/<Subsite>/SiteAssets/FileUpload.js" type="text/javascript"></script>

<div id="divFileUpload"></div>
<input type="button" id="btnUpload" value="Add File"/>

If you want to include any CSS files then include the below line
<link rel="stylesheet" type="text/css" href="/sites/<site>/<subsite>/SiteAssets/any.css"/>

Create & Upload your javascript file(s) ("taskpage.js & FileUpload.js") in SiteAssets/Any Library. 
taskpage.js -> This 'js' will call the button click event
FileUpload.js -> This 'js' will call the File upload & Update Library Columns Functions



taskpage.js Code:

$(document).ready(function(){
$("#btnUpload").on("click",function(){
var successFileUp = uploadFile("1"); // Here I'm passing ID(I'm using this ID with FileName). If you don't have anything then just pass ("")
successFileUp.done(function(){
alert("File Uploaded!!!");});
});
});



FileUpload.js Code:



'use strict';

//Below code is to check the browser support HTML5 & Add Multiple upload control
jQuery(document).ready(function () {
//Here we are mentioning the File upload control as multiple upload control
$('#divFileUpload').html('<input type="file" id="FileUpload" multiple/>'); 
    // Check for FileReader API (HTML5) support.
    if (!window.FileReader) {
        alert('This browser does not support the FileReader API.');
}
});

//Below code is for Upload the file.
// You can upload files up to 2 GB with the REST API.
function uploadFile(ID) {
var deferred = $.Deferred();

    // Define the folder path for this example.
    var serverRelativeUrlToFolder = '<Your Library Location>';    //Ex: '/sites/<Site>/<SubSite>/<LibraryName>';

    // Get test values from the file input and text input page controls.
    var fileInput = jQuery('#FileUpload');    

    // Get the server URL.
    var serverUrl = _spPageContextInfo.webAbsoluteUrl;

// Below Code call all files in a loop, Initiate method calls using jQuery promises.
    // Get the local file as an array buffer.
(function Tasks(i,callback)
{
if(i<fileInput[0].files.length)
{
var success = ProcessFiles(i);
success.done(function(){Tasks((i+1),callback);});
}
else
{
callback();
}
})(0,function(){deferred.resolve();});

//Below function call all the functions (GetFileBuffer,UploadFile,GettheLibraryItem,UpdatingTheItemColumns)
function ProcessFiles(ind)
{
var deferred = $.Deferred();
var getFile = getFileBuffer(ind);

getFile.done(function (arrayBuffer) {

// Add the file to the SharePoint folder.
var addFile = addFileToFolder(arrayBuffer,ind);
addFile.done(function (file, status, xhr) {

// Get the list item that corresponds to the uploaded file.
var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
getItem.done(function (listItem, status, xhr) {

// Change the display name and title of the list item.
var changeItem = updateListItem(listItem.d.__metadata,ind);
changeItem.done(function (data, status, xhr) {
//alert("File "+ind+" uploaded");
deferred.resolve();
});
changeItem.fail(onError);
});
getItem.fail(onError);
});
addFile.fail(onError);
});
getFile.fail(onError);
return deferred.promise();
}


    // Below code Get the local file as an array buffer.
    function getFileBuffer(ind) {
        var deferred = jQuery.Deferred();
        var reader = new FileReader();
        reader.onloadend = function (e) {
            deferred.resolve(e.target.result);
}
        reader.onerror = function (e) {
            deferred.reject(e.target.error);
}
        reader.readAsArrayBuffer(fileInput[0].files[ind]);
        return deferred.promise();
}


// Below code Add the file to the file collection in the Shared Documents folder.
    function addFileToFolder(arrayBuffer,ind) {

        // Get the file name from the file input control on the page.        

var fileName = fileInput[0].files[ind].name;

        // Construct the endpoint.
        var fileCollectionEndpoint = String.format(
"{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
"/add(overwrite=true, url='{2}')",
serverUrl, serverRelativeUrlToFolder, fileName);

        // Send the request and return the response.
        // This call returns the SharePoint file.
        return jQuery.ajax({
            url: fileCollectionEndpoint,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"content-type": "application/json;odata=verbose"
                //"content-length": arrayBuffer.byteLength
}
});
}

 // Below code Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
    function getListItem(fileListItemUri) {

        // Send the request and return the response.
        return jQuery.ajax({
            url: fileListItemUri,
            type: "GET",
            headers: { "accept": "application/json;odata=verbose" }
});
}


// Below code Update the display name and title of the list item.
    function updateListItem(itemMetadata,ind) {
//Adding ID with file name here
var newName =  ID.toString()+'-'+fileInput[0].files[ind].name;
        // Define the list item changes. Use the FileLeafRef property to change the display name. 
        // For simplicity, also use the name as the title. 
        // The example gets the list item type from the item's metadata, but you can also get it from the
        // ListItemEntityTypeFullName property of the list.
        var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}','ParentID':'{3}'}}",
itemMetadata.type, newName, newName, ID);

        // Send the request and return the promise.
        // This call does not return response content from the server.
        return jQuery.ajax({
            url: itemMetadata.uri,
            type: "POST",
            data: body,
            headers: {
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-type": "application/json;odata=verbose",
                //"content-length": body.length,
                "IF-MATCH": itemMetadata.etag,
                "X-HTTP-Method": "MERGE"
}
});
}
return deferred.promise();
}

//Below code for Display error messages. 
function onError(error) {
    alert(error.responseText);
}

Once the files are updated you will get Alert message. Since it is a Ajax call so browser tab will not show the loading symbol.

Comments

Popular posts from this blog

Add content type to SharePoint List/Library using REST API

A type named 'SP.Data. could not be resolved by the model error