8

I want to upload canvas image through formdata/multipart. I have a canvas which generates the image data with toDataURL(). I want to upload image data as formdata/multipart with Ajax post.

Here is the code ....

var dataUrl =  canvas.toDataURL('image/png');
var multipart = new FormData(); 

multipart.append('user_id', userID);
multipart.append('password', pwd);
multipart.append('inputdata',image data here);

 $.ajax({
            type : 'POST',
            // dataType: 'json',
            url : serviceURL,
            data : multipart,
            cache : false,
            processData : false,
            contentType : false,
            success : function(data) {


            },
            error : function(xhr, status, error) {

            }

        });

I know that one can not append the image data uri into FormData. So how can i append this?

Thanks

Arun Bertil
  • 4,452
  • 4
  • 32
  • 58
Pramod Tiwari
  • 161
  • 1
  • 6
  • Try using `canvas.toBlob()` instead of `toDataURL`. You would then need to call `multipart.append('inputdata', canvas.toBlob(), "filename")` (notice the third argument; the filename will default to `"blob"` if you don’t provide it). – Raphael Schweikert Dec 08 '13 at 15:24
  • Possible duplicate of [Convert Data URI to File then append to FormData](http://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata) – Dmitry Shvedov Jan 11 '17 at 19:44

1 Answers1

-4

Try this ?

var dataUrl =  canvas.toDataURL('image/png');
var formData = {
    user_id: userID,
    password: pwd,
    inputdata: dataUrl
}

 $.ajax({
        type : 'POST',
        // dataType: 'json',
        url : serviceURL,
        data : formData,
        cache : false,
        success : function(data) {
        },
        error : function(xhr, status, error) {

        }
    });

// get data on express(nodejs)  server side :
app.post("/postUrl",function(q,s){
    var requestData = q.body;
    console.log(requestData.inputdata);
    //  Output: 
    //  "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
    //  
})
Cyrilis
  • 38
  • 1
  • 3