Sharepoint 2013 Rest Api Upload File C#
Hello All,
Today new discussion, which we implemented in our one of the SharePoint 2013 project.
Background: In 1 of our SharePoint OnPremises projection, we have requirement to upload the user'south photograph, his contour image in SharePoint Image library (PublishingImages). Then we have implemented this characteristic using JavaScript and upload prototype in SharePoint Paradigm library using residuum API.
This become generic component and anybody can apply this in any SharePoint projection. We have used this control in our couple of Visual WebParts.
In this article I'll share step by step details how nosotros implemented and how this component works.
Surround: SharePoint on premises 2013, didn't tested for SharePoint online but I believe it should work for SharePoint online too.
Details: We have OOB FileUpload command available in .NET but which causes page mail dorsum then we decided to implement client side command.
Pace 1: Using <input> chemical element with type "file". This let the user to select one or more files. File input renders the button "Choose File", on click of this button file picker dialog opens and characterization which shows the file name every bit
<input type="file" draggable="true" id="fileupload" class="grade-command" />
Figure 1: SharePoint OnPremises – File Input element
On click of "Choose File" push file open dialog box opens as and we can select the one or multiple files from it. Here in case we required simply 1 file and so because each fourth dimension that just one file will exist selected at a time.
Effigy two: SharePoint OnPremises – Open file dialog box, opens when "Choose File" push is clicked
Step 2: We have added ane more than push button "Upload Profile", on click of this button nosotros are uploading image in SharePoint Images library every bit
Figure 3: SharePoint OnPremises – "Upload Contour" button with File Input command
Step 3: On "Upload Profile" button click we volition upload the selected file using remainder apis, we are calling JavaScript method "UploadFile" as
<input type="button" value="Upload Profile" id="btnUploadProfile" onclick="UploadFile()" />
Here also showing OOB wait dialog box till the prototype go uploaded in SharePoint.
Following are the detailed steps to upload file using remainder API from JavaScript
ane. Get the file element as var fileElement = <%=fileupload.ClientID%>; 2. Check if file is selected or not, if not then showing alert message as if (fileElement.files.length === 0) { alert('No file was selected'); return; }//if (fileElement.files.length === 0) 3. Since we are using Rest API remember happens, we are showing OOB SharePoint wait dialog box till the file is go uploaded in SharePoint Images library as var waitDialog_FileUpload = SP.UI.ModalDialog.showWaitScreenWithNoClose("Contour Image upload in progress", '', eighty, 560); 4. Get the file name as var parts = fileElement.value.split("\\"); var filename = parts[parts.length - i]; 5. Read the file and once done call the rest api as, we are using FileReader object which let us asynchronously read the content of file. There is a FileReader.readyState belongings having possible values of the state are EMPTY 0 No data is loaded yet LOADING 1 Data is currently being loading DONE 2 Read request is done var fileReader = new FileReader(); //File loaded fileReader.onloadend = function (upshot) { if (event.target.readyState == FileReader.Washed) { var filecontent = result.target.upshot; //Lawmaking to upload image in Images Library } 6. Uploading image to Images library using REST APIs //SharePoint images library path var imagelibraryURL = _spPageContextInfo.siteServerRelativeUrl + "PublishingImages"; //Consummate Rest API var completeImageLibraryUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('" + imagelibraryURL + "')/Files/add(url='" + filename + "',overwrite=truthful)"; $.ajax({ url: completeImageLibraryUrl, blazon: "POST", data: filecontent, async: imitation, processData: false, headers: { "accept": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val(), }, consummate: role (data) { var clientContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl); var web = clientContext.get_web(); var fileurl = imagelibraryURL + "/"+filename; var imagetopublish = web.getFileByServerRelativeUrl(fileurl); imagetopublish.checkIn(); imagetopublish.publish(); clientContext.executeQueryAsync(); //close the wait dialog if (waitDialog_FileUpload != null) { waitDialog_FileUpload.close(); } alarm("Your profile image uploaded successfully"); }, //consummate error: office (err) { if (waitDialog_FileUpload != null) { waitDialog_FileUpload.shut(); } alert(err + err.message + err.stacktrace); }//mistake });//$.ajax fileReader.readAsArrayBuffer(fileElement.files[0]);
Complete Code: HTML: <input type="file" draggable="truthful" id="fileupload" class="class-command" /> <input type="push button" value="Upload Profile" id="btnUploadProfile" onclick="UploadFile()" /> JavaScript: office UploadFile() { var fileElement = <%=fileupload.ClientID%>; if (fileElement.files.length === 0) { alert('No file was selected'); return; }//if (fileElement.files.length === 0) else { var waitDialog_FileUpload = SP.UI.ModalDialog.showWaitScreenWithNoClose("Profile Image upload in progress", '', 80, 560); var parts = fileElement.value.split("\\"); var filename = parts[parts.length - 1]; var fileReader = new FileReader(); //File loaded fileReader.onloadend = part (effect) { if (result.target.readyState == FileReader.DONE) { var filecontent = event.target.effect; //Code to upload image in Images Library var imagelibraryURL = _spPageContextInfo.siteServerRelativeUrl + "PublishingImages"; //Complete Remainder API var completeImageLibraryUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('" + imagelibraryURL + "')/Files/add(url='" + filename + "',overwrite=true)"; $.ajax({ url: completeImageLibraryUrl, type: "POST", data: filecontent, async: false, processData: faux, headers: { "accept": "application/json;odata=verbose", "10-RequestDigest": $("#__REQUESTDIGEST").val(), }, complete: function (data) { var clientContext = new SP.ClientContext(_spPageContextInfo.webAbsoluteUrl); var web = clientContext.get_web(); var fileurl = imagelibraryURL + "/"+filename; var imagetopublish = spider web.getFileByServerRelativeUrl(fileurl); imagetopublish.checkIn(); imagetopublish.publish(); clientContext.executeQueryAsync(); //close the look dialog if (waitDialog_FileUpload != cypher) { waitDialog_FileUpload.close(); } alert("Your profile paradigm uploaded successfully"); }, //complete mistake: function (err) { if (waitDialog_FileUpload != nothing) { waitDialog_FileUpload.close(); } alert(err + err.message + err.stacktrace); }//mistake });//$.ajax }// if (event.target.readyState == FileReader.Washed) fileReader.readAsArrayBuffer(fileElement.files[0]); }//else }//UploadFile
References:
- <input type="file">
- FileReader object
- Rest API to upload the file
- OOB SharePoint Wait dialog box
Cheers for reading 🙂
Keep reading, share your thoughts, experiences. Feel gratis to contact us to discuss more. If y'all take whatever suggestion / feedback / incertitude, you are almost welcome.
Stay tuned on Knowledge-Junction, will come up with more such articles
Source: https://knowledge-junction.com/2019/01/18/sharepoint-onpremises-client-side-file-upload-control-and-uploading-file-in-sharepoint-using-rest-api/
0 Response to "Sharepoint 2013 Rest Api Upload File C#"
Post a Comment