Thursday, 13 October 2016

Add Attachment to a List Item using REST api in

SharePoint 2010/2013

Introduction

This article is about how to use REST api to attach file to a list item in SharePoint 2010/2013.

Let's Start

Create a JavaScript function named addFile . Pass ListName and ItemId  as a parameter to addFile function as show below:-

 function addFile(listName,itemId){  
      var allFiles = [];  
      var input = document.getElementById('file');  
      var file = input.files[0];  
      if (file != null && file.size > 0) {  
                          allFiles.push(file);  
      }  
      if (allFiles.length > 0) {                             
                          uploadFile(listName, itemId, allFiles);  
      }  
      else {  
           alert("Please select the Attachment");  
      }          
 }  

UploadFile function is going to attach file to a list item using REST api as show below:-

 function uploadFile(listName, id, file) {  
    var deferred = $.Deferred();  
    var fileName = file.name;  
    getFileBuffer(file).then(  
    function (buffer) {  
     var bytes = new Uint8Array(buffer);  
     var binary = '';  
     for (var b = 0; b < bytes.length; b++) {  
     binary += String.fromCharCode(bytes[b]);  
     }  
     var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";  
     console.log(' File size:' + bytes.length);  
     $.getScript(scriptbase + "SP.RequestExecutor.js", function () {  
     var createitem = new SP.RequestExecutor(_spPageContextInfo.webServerRelativeUrl);  
     createitem.executeAsync({  
      url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + fileName + "')",  
      method: "POST",  
      binaryStringRequestBody: true,  
      body: binary,  
      success: fsucc,  
      error: ferr,  
      state: "Update"  
     });  
     function fsucc(data) {  
      console.log(data + ' uploaded successfully');  
      deferred.resolve(data);  
     }  
     function ferr(data) {  
      console.log(fileName + "not uploaded error");  
      deferred.reject(data);  
     }  
     });  
    },  
    function (err) {  
     deferred.reject(err);  
    }  
    );  
    return deferred.promise();  
   }  

  Convert file to stream of bytes using FileReader() Object .

 function getFileBuffer(file) {   
            var deferred = $.Deferred();   
            var reader = new FileReader();   
            reader.onload = function (e) {   
              deferred.resolve(e.target.result);   
            }   
            reader.onerror = function (e) {   
              deferred.reject(e.target.error);   
            }   
            reader.readAsArrayBuffer(file);   
            return deferred.promise();   
         }   

1 comment: