Quantcast
Channel: Sam's Activities
Viewing all articles
Browse latest Browse all 3363

Set the metadata of a SharePoint file using REST

$
0
0

Introduction:

In our earlier blog, we discussed about creating folders and uploading files on the SharePoint Online through workflows/plugins using REST.

In this blog, we will see how we can set the metadata of the uploaded files using REST.

Below is the code snippet to set the metadata of a file using REST:

//Here first create the JSON string of file metadata
string result = @"{'__metadata': { 'type': 'SP.ListItem'}, 'Aliases':'My File.docx', 'Owner':'CRM Owner', 'Date':'1/7/2017'}";
string siteUrl = “https://crmtrial.sharepoint.com”
Uri spSite = new Uri(siteUrl);
private SpoAuthUtility _spo = SpoAuthUtility.Create(spSite, _username, WebUtility.HtmlEncode(_password), false);
//read the digest
string digest = _spo.GetRequestDigest();
//convert JSON data to bytes
byte[] content = ASCIIEncoding.ASCII.GetBytes(result);

//define the file URL to set the metadata
string fileURL = Account/Test Account Folder/TestFile.docx;
var requestUrl = string.Format("{0}/_api/web/GetFileByServerRelativeUrl('{1}')/ListItemAllFields", siteURL, fileURL);

var webRequest = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
                webRequest.Headers.Add("X-RequestDigest", digest);
                webRequest.Headers.Add("X-HTTP-Method", "PATCH");
                webRequest.Headers.Add("If-Match", "*");
                webRequest.Accept = "application/json;odata=verbose";
                webRequest.ContentType = "application/json;odata=verbose";
                webRequest.Method = "POST";

                // Send a json odata request to SPO rest services to fetch all list items for the list.
                byte[] result = HttpHelper.SendODataJsonRequest(
                  new Uri(requestUrl),
                  "POST", // reading data from SP through the rest api usually uses the GET verb
                  content,
                  webRequest,
                  _spo // pass in the helper object that allows us to make authenticated calls to SPO rest services
                  );

                //read the response
                string response = Encoding.UTF8.GetString(result, 0, result.Length);

If you go to the uploaded file’s properties in SharePoint, you can see the metadata of the file as shown in the screenshot below;

Set the metadata of a SharePoint file using REST

Hope this helps!

Click2Clone One Click Productivity App to Copy_clone Dynamics 365_CRM Records


Viewing all articles
Browse latest Browse all 3363

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>