Sharepoint - sharepoint 2013 rest api upload image
I solved my problem Read file as an readAsArrayBuffer(file) pass that file.target.result as buffer in _arrayBufferToBase64
function _arrayBufferToBase64(buffer) {
var binary = ''
var bytes = new Uint8Array(buffer)
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i])
}
return binary;
}
here return of binary variable pass as content in uploadfile function
function uploadfile(name, content) {
var createitem = new SP.RequestExecutor(appweburl);
createitem.executeAsync({
url: appweburl + "/_api/web/GetFolderByServerRelativeUrl('/sites/Tile of web/app title/Lists/list name/foldername')/Files/Add(url='" + name + "',overwrite=true)",
method: "POST",
binaryStringRequestBody: true,
body: content,
success: function (e) {
alert('done');
},
error: function () { alert("Error"); },
state: "Update"
});
}
You need to convert the image to binary data which you can pass as content. One way is to use below :
function getBase64Image() {
//if file:// dont work on your browser, you can find other alternatives.
var img = new Image();
img.src = "file:///c:/images/image-to-upload.png";
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to guess the
// original format, but be aware the using "image/jpg" will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}