Add Attachments to List Items in SharePoint 2013 Using REST API

Introduction

Welcome to the SharePoint 2013 REST Series. In my previous article, we saw how to delete list items in SharePoint using REST API.

In this article, we will discuss how to add an attachment to list items in a SharePoint List using the REST API.

The SharePoint 2013 environment adds the ability to remotely interact with SharePoint sites using REST. So you can talk to SharePoint objects using any technology that supports standard REST capabilities. In this way, SharePoint data can be accessed anywhere and everywhere.

List of REST Access Points

The following is a list of access points that gives you entry into granular access points.

  • Site

    http://server/site/_api/site
     
  • Web

    http://server/site/_api/web
     
  • User Profile

    http:// server/site/_api/SP.UserProfiles.PeopleManager
     
  • Search

    http:// server/site/_api/search
     
  • Publishing

    http:// server/site/_api/publishing

List of REST End Points

The following is a list of End points whichare the most commonly used in a SharePoint list.

  • http://server/site/_api/web/lists
  • http://server/site/_api/lists/getbytitle('listname')
  • http://server/site/_api/web/lists(‘guid’)
  • http://server/site/_api/web/lists/getbytitle(‘Title’)

Note: The following code is tested in my SP 2013 online environment.

Step 1: Before writing your code, please ensure you have sufficient permission to access cross-domain requests. So I have given full permission to all the contents listed below.

Tenant

Full Permission

Site Collection

Full Permission

Web

Full Permission

List

Full Permission

Permission 

Step 2: Navigate to the App.js file then copy the following code and paste it in.
 
Code
  1. 'use strict';  
  2. var hostweburl;   
  3. var appweburl;   
  4.    
  5.     // This code runs when the DOM is ready and creates a context object which is   
  6.     // needed to use the SharePoint object model  
  7.     $(document).ready(function () {  
  8.           
  9.             //Get the URI decoded URLs.   
  10.     hostweburl =   
  11.         decodeURIComponent(   
  12.             getQueryStringParameter("SPHostUrl"));   
  13.     appweburl =   
  14.         decodeURIComponent(   
  15.             getQueryStringParameter("SPAppWebUrl"));   
  16.                // Resources are in URLs in the form:  
  17.         // web_url/_layouts/15/resource  
  18.         var scriptbase = hostweburl + "/_layouts/15/";    
  19.    
  20.         // Load the js file and continue to load the page with information about the list top level folders.  
  21.         // SP.RequestExecutor.js to make cross-domain requests  
  22.           
  23.          // Load the js files and continue to the successHandler  
  24.             $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);  
  25.              });  
  26.               
  27.              // Function to prepare and issue the request to get  
  28.           //  SharePoint data  
  29.   function execCrossDomainRequest() {  
  30.             // executor: The RequestExecutor object  
  31.             // Initialize the RequestExecutor with the app web URL.  
  32.             var executor = new SP.RequestExecutor(appweburl);             
  33.               
  34.             var metatdata = " This is the content of a file added through REST API";  
  35.             var digest = $("#__REQUESTDIGEST").val();  
  36.   
  37.             // Issue the call against the app web.  
  38.             // To get the title using REST we can hit the endpoint:  
  39.             //      appweburl/_api/web/lists/getbytitle('listname')/items  
  40.             // The response formats the data in the JSON format.  
  41.             // The functions successHandler and errorHandler attend the  
  42.             //      sucess and error events respectively.  
  43.             executor.executeAsync(  
  44.                 {         
  45.           url:   
  46.             appweburl +   
  47.             "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('CustomList')/items(1)/AttachmentFiles/add(FileName='mycustom.txt')?@target='" +   
  48.             hostweburl + "'",   
  49.         method: "POST",   
  50.         data: metatdata ,           
  51.          headers: {          
  52.         "X-RequestDigest": digest, "Accept""application/json; odata=verbose"},                      
  53.             success: function (data) {  
  54.                 alert("success: " + JSON.stringify(data));  
  55.             },  
  56.             error: function (err) {  
  57.                 alert("error: " + JSON.stringify(err));  
  58.             }   
  59.                 }           
  60.             );                             
  61.           }                    
  62.     // This function prepares, loads, and then executes a SharePoint query to get   
  63.     // the current users information  
  64.       
  65. //Utilities   
  66.    
  67. // Retrieve a query string value.   
  68. // For production purposes you may want to use   
  69. // a library to handle the query string.   
  70. function getQueryStringParameter(paramToRetrieve) {   
  71.     var params =   
  72.         document.URL.split("?")[1].split("&");     
  73.     for (var i = 0; i < params.length; i = i + 1) {   
  74.         var singleParam = params[i].split("=");   
  75.         if (singleParam[0] == paramToRetrieve)   
  76.             return singleParam[1];   
  77.     }   
  78. }   
  79.    
  80. //Retrieve the form digest value.      
  81. //Store the value of the form digest.   
  82. function contextSuccessHandler(data) {   
  83.     alert("List Created Successfully");  
  84. }    
  85. function contextErrorHandler(data, errorCode, errorMessage) {   
  86.     alert(data);  
  87.     alert(errorCode);  
  88.     alert("Could not get context info: " + errorMessage);   
  89. }  
Screenshot

code
Code1
Code2

Step 3: When deploying, you will be prompted with the following screen. Press Trust it and proceed with the deployment.

deploying

Code Walkthrough

A. Post Method in REST API

SharePoint 2013 REST service supports sending POST commands that include object definitions to endpoints that represent collections. In this example, Test List is a custom SharePoint list where list items are updated.

B. Request Executor.JS

The cross-domain library lets you interact with more than one domain in your remote app page through a proxy. SP.RequestExecutor.js acts as a cross-domain library to fetch or create a SharePoint list from your APP domain.
  1. function execCrossDomainRequest() {  
  2.             // executor: The RequestExecutor object  
  3.             // Initialize the RequestExecutor with the app web URL.  
  4.             var executor = new SP.RequestExecutor(appweburl);           var metatdata = "{ '__metadata': { 'type': 'SP.Data.TestListListItem' }, 'Title': 'changelistitemtitle'}"
Output

Output

Summary

I hope this article helps you.