Share via


Uploading File to SharePoint Online Document Library Using REST API

//added validation for httpwebresponse

Used provider hosted app so we need to pass token which in this case is appOnlyAccessToken as mentioned in below code. All we need to do is create HttpWebRequest and get a response by adding token.headers as below:                           

HttpWebRequest endpointRequest;
                            endpointRequest = (HttpWebRequest)HttpWebRequest.Create(hostWeb + "/_api/web/GetFolderByServerRelativeUrl('" + strLibraryName + "/" + destination + strFolderPath + "')/Files/add(url='" + strFileName + "',overwrite=true)");
                            endpointRequest.Method = "POST";
                            endpointRequest.Headers.Add("binaryStringRequestBody", "true");
                            endpointRequest.Headers.Add("Authorization", "Bearer " + appOnlyAccessToken);
                            endpointRequest.GetRequestStream().Write(translatedText, 0, translatedText.Length);
 
                             
if(HttpStatusCode.OK == endpointRequest.GetResponse().StatusCode)
{
                            HttpWebResponse endpointresponse = (HttpWebResponse)endpointRequest.GetResponse();
}
where
hostWeb = o365 site
strLibararyName= name of doc library of sharepoint
Destination ,path=folder path
strfilename=name of file with extension

Please add if something is missed or icnorrect

below is code to get apponlyaccesstoken

hostWeb = Page.Request["SPHostUrl"];
            var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);
Uri sharepointUrl = new  Uri(hostWeb);
                SharePointContextToken appOnlyContextToken = TokenHelper.ReadAndValidateContextToken(contextToken, Request.Url.Authority);
                string appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(appOnlyContextToken.TargetPrincipalName, sharepointUrl.Authority, appOnlyContextToken.Realm).AccessToken;

Other Languages