In one of our SharePoint OnPremises projects, we had this requirement to upload the user’s profile image in SharePoint Image library (PublishingImages). So, we implemented this feature using JavaScript and uploaded the image in SharePoint Image library using REST API.
This becomes a generic component and anybody can use this in any SharePoint project. We have used this Control in our couple of Visual WebParts.
In this article, I’ll share step by step details how we implemented and how this component worked.
Environment
SharePoint on premises 2013, didn’t test for SharePoint online but I believe it should work for SharePoint online as well.
Details
We have OOB FileUpload control available in .NET but which causes page postback so we decided to implement client-side control.
Step 1
Use <input> element with type “file”. This lets the user select one or more files. File input renders the button “Choose File”. On click of this button, file picker dialog opens with a label which shows the file name.
- <input type="file" draggable="true" id="fileupload" class="form-control" />
Figure 1: File Input element
On click of “Choose File” button, "file open" dialog box opens and we can select one or multiple files from it. Here, in this case, we require only one file and so only one file will be selected at a time.
Figure 2: Open file dialog box, opens when "Choose File" button is clicked
Step 2
We have added one more button “Upload Profile”. On click of this button, we are uploading image in SharePoint Images library.
Figure 3: "Upload Profile" button with File Input control
Step 3
On “Upload Profile” button click, we will upload the selected file using REST APIs. We are calling JavaScript method “UploadFile”.
- <input type="button" value="Upload Profile" id="btnUploadProfile" onclick="UploadFile()" />
Here also, it is showing OOB wait dialog box till the image gets uploaded in SharePoint.
Following are the detailed steps to upload file using rest API from JavaScript
- Get the file element.
- var fileElement = <%=fileupload.ClientID%>;
- Check if file is selected or not, if not then showing alert message.
- if (fileElement.files.length === 0) {
- alert('No file was selected');
- return;
- }
- Since we are using REST API call back happens, we are showing OOB SharePoint wait dialog box till the file is get uploaded in SharePoint Images library.
- var waitDialog_FileUpload = SP.UI.ModalDialog.showWaitScreenWithNoClose("Profile Image upload in progress", '', 80, 560);
- Get the file name.
- var parts = fileElement.value.split("\\");
- var filename = parts[parts.length - 1];
- Read the file and once done, call the REST API. We are using FileReader object which lets us asynchronously read the content of file. There is a FileReader.readyState property 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();
-
- fileReader.onloadend = function (event) {
- if (event.target.readyState == FileReader.DONE) {
- var filecontent = event.target.result;
-
-
- }
- Upload the image to Images library using REST APIs.
-
- var imagelibraryURL = _spPageContextInfo.siteServerRelativeUrl +
- "PublishingImages";
-
-
- var completeImageLibraryUrl = _spPageContextInfo.webAbsoluteUrl
- + "/_api/web/GetFolderByServerRelativeUrl('" + imagelibraryURL +
- "')/Files/add(url='" + filename + "',overwrite=true)";
-
-
- $.ajax({
- url: completeImageLibraryUrl,
- type: "POST",
- data: filecontent,
- async: false,
- processData: false,
- headers: {
- "accept": "application/json;odata=verbose",
- "X-RequestDigest": $("#__REQUESTDIGEST").val(),
- },
- complete: function (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();
-
- if (waitDialog_FileUpload != null) {
- waitDialog_FileUpload.close();
- }
- alert("Your profile image uploaded successfully");
- },
- error: function (err) {
- if (waitDialog_FileUpload != null) {
- waitDialog_FileUpload.close();
- }
- alert(err + err.message + err.stacktrace);
- }
- });
-
- fileReader.readAsArrayBuffer(fileElement.files[0]);
Complete Code
HTML
- <input type="file" draggable="true" id="fileupload" class="form-control" />
- <input type="button" value="Upload Profile" id="btnUploadProfile" onclick="UploadFile()" />
JS
- function UploadFile() {
- var fileElement = <%=fileupload.ClientID%>;
- if (fileElement.files.length === 0) {
- alert('No file was selected');
- return;
- }
- 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();
-
- fileReader.onloadend = function (event) {
- if (event.target.readyState == FileReader.DONE) {
- var filecontent = event.target.result;
-
-
- var imagelibraryURL = _spPageContextInfo.siteServerRelativeUrl +
- "PublishingImages";
-
-
- var completeImageLibraryUrl = _spPageContextInfo.webAbsoluteUrl
- + "/_api/web/GetFolderByServerRelativeUrl('" + imagelibraryURL +
- "')/Files/add(url='" + filename + "',overwrite=true)";
-
-
- $.ajax({
- url: completeImageLibraryUrl,
- type: "POST",
- data: filecontent,
- async: false,
- processData: false,
- headers: {
- "accept": "application/json;odata=verbose",
- "X-RequestDigest": $("#__REQUESTDIGEST").val(),
- },
- complete: function (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();
-
- if (waitDialog_FileUpload != null) {
- waitDialog_FileUpload.close();
- }
- alert("Your profile image uploaded successfully");
- },
- error: function (err) {
- if (waitDialog_FileUpload != null) {
- waitDialog_FileUpload.close();
- }
- alert(err + err.message + err.stacktrace);
- }
- });
- }
- fileReader.readAsArrayBuffer(fileElement.files[0]);
-
- }
- }
References
- <input type="file">
- FileReader object
- Rest API to upload the file
- OOB SharePoint Wait dialog box