C# Http Method How to Upload Document into SharePoint Online Document Library


In this article we will see how to upload file into SharePoint Online Document Library using REST API

and HTTP method. Also you will drr how to get the document ID of the same upload document.

Here is the code:

            string filePath = @"C:\MyFile.pdf";

            string siteUrl = "https://domainname.sharepoint.com/sites/contoso5/"

            byte[] bytefile = System.IO.File.ReadAllBytes(filePath);

            HttpWebRequest endpointReq = (HttpWebRequest)HttpWebRequest.Create(siteUrl + "/_api/web/GetFolderByServerRelativeUrl('DocLib/MyFolder')/Files/add(url='Myfile.pdf',overwrite=true)?$expand=ListItemAllFields");

            endpointReq.Method = "POST";

            endpointReq.Headers.Add("binaryStringRequestBody", "true");

            endpointReq.Headers.Add("Authorization", "Bearer " + GetAccessToken());

            endpointReq.GetRequestStream().Write(bytefile, 0, bytefile.Length);

            var endpointresp = (HttpWebResponse)endpointReq.GetResponse();

            using (var sreader = new StreamReader(endpointresp.GetResponseStream()))

            {

                var resp = sreader.ReadToEnd();
                 // You can deserialize 'resp' further to get document ID and other field values of uploaded document.

            }

Note: the query $expand=ListItemAllFields used in the REST API will get all fields and values of the uploaded document on SharePoint Online. Including ID of the uploaded document.


Happy PC (Programming / Configuring)

Comments

Popular posts from this blog

In C# CSOM How to Delete Folders Recursively, Sub-Folders, Files in SharePoint Online Document Library

How Get, Set, Delete Permission on SharePoint Online Site using Graph API

What is SharePoint online default authentication method? And which credential flow it is using to authenticate?