locked
Upload files using REST API in SharePoint 2013 RRS feed

  • Question

  • Hi,

    I am trying to use the REST API to call the document library and upload the files. I have verified the MSDN and got the below code

    url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files/add(url='a.txt',overwrite=true) method: POST body: "Contents of file" Headers: Authorization: "Bearer " + accessToken X-RequestDigest: form digest value content-length:length of post body

    How we can call this code in the SharePoint page to upload the files. I am not sure how we need to get the "AccessToken" and to call this code in the sharepoint page.

    If you have any sample code or reference link,please send it to me.

    Thank you,

    Mylsamy


    Wednesday, May 28, 2014 8:40 PM

Answers

  •  Thank you , I am able to get the access token and able to upload the files.

     private static string GetFormDigest(string webUrl)
        {
            //Validate input
            if (String.IsNullOrEmpty(webUrl) || String.IsNullOrWhiteSpace(webUrl))
                return String.Empty;
            //Create REST Request
            Uri uri = new Uri(webUrl + "/_api/contextinfo");
            HttpWebRequest restRequest = (HttpWebRequest)WebRequest.Create(uri);
            CredentialCache credNewCache = new CredentialCache();
            credNewCache.Add(uri,"NTLM",CredentialCache.DefaultNetworkCredentials);     
            restRequest.Credentials = credNewCache;
            restRequest.Method = "POST";
            restRequest.ContentLength = 0;

            //Retrieve Response
            HttpWebResponse restResponse = (HttpWebResponse)restRequest.GetResponse();
            XDocument atomDoc = XDocument.Load(restResponse.GetResponseStream());
            XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
            //Extract Form Digest
            return atomDoc.Descendants(d + "FormDigestValue").First().Value;
        }

    Thank you,

    Mylsamy

    Friday, May 30, 2014 6:00 PM

All replies

  • Hi,

    You can take the code demo below for a try, it will upload a file to Document Library after you make your selection with the File control:

    <script type="text/javascript" src="../SiteAssets/js/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
    
    //Function attached to the html fileupload tag (<input type="file">)
    function uploadFile(){
        if (document.getElementById("file").files.length === 0) {
            alert('No file was selected');
            return;
        }
        var parts = document.getElementById("file").value.split("\\");
        var filename = parts[parts.length - 1];
        var file = document.getElementById("file").files[0];
        uploadFileSync("https://yoursite", "Documents", filename, file);
    }
    
    //Upload file synchronously
    function uploadFileSync(spWebUrl , library, filename, file) 
    {
        var reader = new FileReader();
        reader.onloadend = function(evt) 
        {
          if (evt.target.readyState == FileReader.DONE) 
          {
             var buffer = evt.target.result;
             var completeUrl = spWebUrl
               + "/_api/web/lists/getByTitle('"+ library +"')"
               + "/RootFolder/Files/add(url='"+ filename +"',overwrite='true')?"
               + "@TargetLibrary='"+library+"'&@TargetFileName='"+ filename +"'";
    
              $.ajax({
                    url: completeUrl,
                    type: "POST",
                    data: buffer,
                    async: false,
                    processData: false,
                    headers: {
                        "accept": "application/json;odata=verbose",
                        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                        "content-length": buffer.byteLength
                    },
                    complete: function (data) {
                        //uploaded pic url
                        console.log(data.responseJSON.d.ServerRelativeUrl);
                    },
                    error: function (err) {
                         alert('failed');
                    }
                });
            
          }
        };
        reader.readAsArrayBuffer(file);
    }
    
    
    </script>
    <input type="file" id='file' onchange="uploadFile()"/>

    Thanks

    Patrick Liang

    Forum Support

    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com



    Patrick Liang
    TechNet Community Support



    Thursday, May 29, 2014 12:05 PM
  • Hi,

     Please refer the below forum which will give you detailed idea on the REST api.

    http://blogs.msdn.com/b/uksharepoint/archive/2013/04/20/uploading-files-using-the-rest-api-and-client-side-techniques.aspx

    If you need more information to implement, please let us know


    Sekar - Our life is short, so help others to grow

    Whenever you see a reply and if you think is helpful, click "Alternate TextVote As Helpful"! And whenever you see a reply being an answer to the question of the thread, click "Alternate TextMark As Answer

    Thursday, May 29, 2014 12:16 PM
  •  Thank you , I am able to get the access token and able to upload the files.

     private static string GetFormDigest(string webUrl)
        {
            //Validate input
            if (String.IsNullOrEmpty(webUrl) || String.IsNullOrWhiteSpace(webUrl))
                return String.Empty;
            //Create REST Request
            Uri uri = new Uri(webUrl + "/_api/contextinfo");
            HttpWebRequest restRequest = (HttpWebRequest)WebRequest.Create(uri);
            CredentialCache credNewCache = new CredentialCache();
            credNewCache.Add(uri,"NTLM",CredentialCache.DefaultNetworkCredentials);     
            restRequest.Credentials = credNewCache;
            restRequest.Method = "POST";
            restRequest.ContentLength = 0;

            //Retrieve Response
            HttpWebResponse restResponse = (HttpWebResponse)restRequest.GetResponse();
            XDocument atomDoc = XDocument.Load(restResponse.GetResponseStream());
            XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
            //Extract Form Digest
            return atomDoc.Descendants(d + "FormDigestValue").First().Value;
        }

    Thank you,

    Mylsamy

    Friday, May 30, 2014 6:00 PM
  • Hi Mylsamy,

     if this thread solved your problem, please mark it as answer. So that other developers will get benefit.


    Sekar - Our life is short, so help others to grow

    Whenever you see a reply and if you think is helpful, click "Alternate TextVote As Helpful"! And whenever you see a reply being an answer to the question of the thread, click "Alternate TextMark As Answer

    Monday, June 2, 2014 7:43 AM