Skip to content Skip to sidebar Skip to footer

Converting Base64 Image To Multipart/form-data And Sending With JQuery

I have a base64 encoded jpg in javascript which I would like to post to a server which is expecting multipart/form-data. Specifically, to the pivotal tracker API, which has an exam

Solution 1:

Fairly straight forward. I tried it with JQuery as you did, but couldn't accomplish it. So I went ahead and build my own XHR implementation that will send a custom multipart body to the server.

1) Initialize your XHR 2) Build the multipart body together 3) Send it

var xhr  = new XMLHttpRequest();
...
xhr.open("POST", url, true);

var boundary = '------multipartformboundary' + (new Date).getTime(),
dashdash = '--',
crlf = '\r\n',

This is were the magic happens. You build your own "body" for the transmission and put the image data as a normal variable with name into the body:

content = dashdash+boundary+crlf+'Content-Disposition: form-data; name="NAMEOFVARIABLEINPHP";"'+crlf+crlf+VARIABLEWITHBASE64IMAGE+crlf+dashdash+boundary+dashdash+crlf;

Then just send it of:

xhr.setRequestHeader("Content-type", "multipart/form-data; boundary="+boundary);
xhr.setRequestHeader("Content-length", content.length);
xhr.setRequestHeader("Connection", "close");
// execute
xhr.send(content);

If you use PHP, you have a new variable in your $_POST containing the base64 encoded string. This will prevent that the browser is breaking the string into 72 chars/line and stripping out the +'s and other special chars.

Hope that helps.


Solution 2:

All you need to do is convert base64 data to blob and send it via FormData

function b64toBlob(b64Data, contentType, sliceSize) {
            contentType = contentType || '';
            sliceSize = sliceSize || 512;

            var byteCharacters = atob(b64Data);
            var byteArrays = [];

            for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
                var slice = byteCharacters.slice(offset, offset + sliceSize);

                var byteNumbers = new Array(slice.length);
                for (var i = 0; i < slice.length; i++) {
                    byteNumbers[i] = slice.charCodeAt(i);
                }

                var byteArray = new Uint8Array(byteNumbers);

                byteArrays.push(byteArray);
            }

          var blob = new Blob(byteArrays, {type: contentType});
          return blob;
}


function imagetoblob(ImgId){
    var ImageURL = document.getElementById(ImgId).getAttribute('src');
    // Split the base64 string in data and contentType
    var block = ImageURL.split(";");
    // Get the content type of the image
    var contentType = block[0].split(":")[1];// In this case "image/gif"
    // get the real base64 content of the file
    var realData = block[1].split(",")[1];// In this case "R0lGODlhPQBEAPeoAJosM...."

    // Convert it to a blob to upload
    return b64toBlob(realData, contentType);
}

In your form data

formData.append("image", imagetoblob('cropped_image'));

Post a Comment for "Converting Base64 Image To Multipart/form-data And Sending With JQuery"