Ramesh Palaniappan

Ramesh Palaniappan

  • NA
  • 11k
  • 2.4m

Upload image to picture library using REST

Jul 30 2013 3:15 AM
How to Upload picture to Picture library using REST API and JavaScript in SharePoint 2013. I uploaded image, but image content is not coming. How to read image file to upload in sharepoint.
This is Code is used:

function
ProcessUploadPic() {
if (document.getElementById("inputPic").files.length === 0) {
alert(
"Select a file!");
return;
}
var parts = document.getElementById("inputPic").value.split("\\");
var filename = parts[parts.length - 1];
var fileInput = document.getElementById("inputPic").files[0];
var picReader = new FileReader();
picReader.addEventListener(
"load", function (event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML =
"<img class='thumbnail' src='" + picFile.result + "'" + "title='" + picFile.name + "'/>";
PerformUploadPic(filename, div)
});
picReader.readAsDataURL(fileInput);
}

function
PerformUploadPic(filename, fileData) {
var url = document.URL.split('/');
url = url[0] +
"//" + url[2] + "/" + url[3] + "/";
$.ajax({
url: url +
"_api/web/getfolderbyserverrelativeurl('Image')/files/add(url='" + filename + "', overwrite=true)",
method:
"POST",
binaryStringRequestBody:
true,
body: fileData,
headers: {
"accept": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-length": fileData.byteLength
},
success:
function (data) {
alert(
"Success! Your Picture was uploaded to SharePoint.");
},
error:
function onQueryErrorAQ(xhr, ajaxOptions, thrownError) {
alert(
'Error:\n' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);
},
state:
"Update"
});
}

Answers (2)