11

I want to upload image or create image in Sharepoint 2013 document library using rest api (Javascript)

my code to get bite array from input type file element is

       var reader = new FileReader();
        reader.onload = function (e) {                   
            var byteArray = new Uint8Array(e.target.result);
            uploadfile(file.name, byteArray);
        }
        reader.readAsArrayBuffer(file);

// this is function to upload file

       function uploadfile(name, content) {

    var createitem = new SP.RequestExecutor(appweburl);
    createitem.executeAsync({
        url: appweburl + "/_api/web/GetFolderByServerRelativeUrl('/sites/Filer/Filer/Lists/DropBoard/" + currentuser + "')/Files/Add(url='"+ name +"',overwrite=true)",
        method: "POST",
        headers: { "Accept": "application/octet-stream", "x-requestforceauthentication": true},
        body: content,
        success: function () { alert("done"); },
        error: function () { alert("Error"); },        
    });    
}

when I upload image this error found in consol Invalid field or parameter requestInfo.body.

2 Answers 2

9

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"
 });
}
1
  • How do I update/set metadata with this?
    – Paul Vu
    May 6, 2020 at 17:41
2

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,/, "");
}
2
  • 1
    i try both passing byte array and base 64. Image uploaded but corrupted. why? Dec 31, 2012 at 8:56
  • try to remove the line dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); from above function Dec 31, 2012 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.