Monday, 22 October 2018

Upload files into a folder of SharePoint Document Library - REST API

Upload files into a folder of SharePoint Document Library - REST API 

var arrayBuffer;  

 <input type="file" name="attachment" id="inputFileUpload" class="input-file-control"/>

function uploadFiles(fileInputControlId, webUrl, documentLibraryName, folderName) {
         for (var i = 0; i < $(fileInputControlId)[0].files.length; i++) {
             var uploadFile = $(fileInputControlId)[0].files[i];
             var getFile = getFileBuffer(uploadFile);
             getFile.done(function (arrayBuffer) {
                 uploadFileToFolder(webUrl, documentLibraryName, folderName, uploadFile.name, arrayBuffer, function (data) {
                   alert("File upload done successfully");
                 }, function (data) {
                   alert("File uploading fail");
                 });
             });
         }
     }


 //Get the uploaded file buffer.
 function getFileBuffer(uploadFile) {
         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(uploadFile);
         return deferred.promise();
     }



//Upload files into SharePoint library with REST API
 function uploadFileToFolder(webUrl, documentLibraryName, folderName, fileName, arrayBuffer, success, failure) {
         //file added to the subfolder of Rootfolder.
         var apiUrl = webUrl + "/_api/web/lists/getByTitle('" + documentLibraryName + "')/RootFolder/folders('" + folderName + "')/files/add(url='" + fileName + "', overwrite=true)";

         $.ajax({
             url: apiUrl,
             type: "POST",
             data: arrayBuffer,
             processData: false,
             async:false,
             headers: {
                 "accept": "application/json;odata=verbose",
                 "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
             },
             success: function (data) {
                 success(data);
             },
             error: function (data) {
                 failure(data);
             }
         });
     }

Create file in SharePoint document library using REST API

Create file in SharePoint document library using REST API

$( document ).ready(function() {

    createlist();

});




function createlist()
{


var content = "Hello, this text is inside the file created with REST API";
var digest = $("#__REQUESTDIGEST").val();
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('/PerformanceDocuments/')/Files/add(overwrite=true, url='test.txt')";
jQuery.ajax({
    url: url,
    type: "POST",
    data: content,
    headers: {        
        "accept": "application/json;odata=verbose", 
        "X-RequestDigest": digest       
    },
    success: function(data){
        console.log(data);
    },
    error: function(data){
        console.log(data);
    }
});
}

Create List Item Using Rest API

Create List Item Using Rest API

function UploadItemToList()
{
 
 var Emp = $("#txtname").val();  
    
    $.ajax  
        ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee')/items",  
        type: "POST",  
        data: JSON.stringify  
        ({  
            __metadata:  
            {  
                type: "SP.Data.EmployeeListItem"  
            },  
            Title: Emp
        }),  
        headers:  
        {  
            "Accept": "application/json;odata=verbose",  
            "Content-Type": "application/json;odata=verbose",  
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
            "X-HTTP-Method": "POST"  
        },  
        success: function(data, status, xhr)  
        {  
              
        },  
        error: function(xhr, status, error)  
        {  
             
        }  
    });  

}

Get the list item using Rest API

Get the list item using Rest API


function GetListItem() {
    var siteUrl = window.location.protocol + '//' + window.location.host + _spPageContextInfo.siteServerRelativeUrl;

    $.ajax({

        url: siteUrl + "/_api/lists/getbytitle('Your List Name')/Items",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function(data) {

            var results = data.d.results;

            for (var i = 0; i < results.length; i++) {

                alert(results[i]["Field name"]);


            }

        },
        error: function() {
            console.log('Failed.');
        }
    });
}