Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

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"
 });
}
share|improve this answer
add comment

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,/, "");
}
share|improve this answer
1  
i try both passing byte array and base 64. Image uploaded but corrupted. why? –  Vishal_Sharepoint Dec 31 '12 at 8:56
    
try to remove the line dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); from above function –  Amit Kumawat Dec 31 '12 at 11:19
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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