Hi,
In my last post, I have explained how to create a sub site using REST from and Console application. In this blog will explain how we can upload a file, which is located in file system, will be uploaded to sharepoint Document library. So if I brief about requirement here:
- Need to upload a file to already created SharePoint site.
- Use REST(not even CSOM) will be used in order to create.
- API call will be send from some other machine(not SharePoint machine) which is in same domain and can access the SharePoint site.
Follow the given steps to achieve the same:
1) Create a simple console application with c# selected language.
2) Next is to install the Newtonsoft.Json. Navigate to Visual studio menu: “View” > “Other Windows” > “Package Manager Console” and Then type the following: “Install-Package Newtonsoft.Json”
3) Now install RestSharp using the package manager. Type the following: “Install-Package RestSharp”
4) Now open the Program.cs file of console application and paste the code below:
string siteurl = “http://sharepoitsite/sites/subsite”; //site on which file needs to be uploaded (don’t put / at end)
string documentlibrary = “Documents”; //Document library where file needs to be uploaded
string filePath = @”C:\Users\mohit.vashishtha\Desktop\test.html”;
byte[] binary = System.IO.File.ReadAllBytes(filePath);
string fname = System.IO.Path.GetFileName(filePath);
string result = string.Empty;
//Url to upload file
string resourceUrl = string.Format(“{0}/_api”,siteurl);
RestClient RC = new RestClient(resourceUrl);
NetworkCredential NCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
RC.Authenticator = new NtlmAuthenticator(NCredential);
Console.WriteLine(“Creating Rest Request”);
RestRequest Request = new RestRequest(“contextinfo?$select=FormDigestValue”, Method.POST);
Request.AddHeader(“Accept”, “application/json;odata=verbose”);
Request.AddHeader(“Body”, “”);
string ReturnedStr = RC.Execute(Request).Content;
int StartPos = ReturnedStr.IndexOf(“FormDigestValue”) + 18;
int length = ReturnedStr.IndexOf(@”””,”, StartPos) – StartPos;
string FormDigestValue = ReturnedStr.Substring(StartPos, length);
Console.WriteLine(“Uploading file Site……”);
resourceUrl = string.Format(“/web/GetFolderByServerRelativeUrl(‘{0}’)/Files/add(url='{1}’,overwrite=true)”, documentlibrary ,fname);
Request = new RestRequest(resourceUrl, Method.POST);
Request.RequestFormat = DataFormat.Json;
Request.AddHeader(“Accept”, “application/json;odata=verbose”);
Request.AddHeader(“X-RequestDigest”, FormDigestValue);
Console.WriteLine(“File is successfully uploaded to sharepoint site.”);
Console.ReadLine();
5) Now application is ready to run. Make sure that all the namespace issues are resolved.
6) It will take some time to create site but output window will display the details it got from the Request.
In case of already existing site:
Hope this information is helpful to you. Thanks for time.
Happy SharePointing 🙂