Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 example curl call like so:

curl -H "X-TrackerToken: TOKEN" -X POST -F Filedata=@/path/to/file \
http://www.pivotaltracker.com/services/v3/projects/PROJECT_ID/stories/STORY_ID/attachments

I have basic XML only calls to their API working fine, using .ajax like so:

$.ajax({
  url: 'http://www.pivotaltracker.com/services/v3/projects/158325/stories',
  type: 'POST',
  contentType: 'application/xml',
  dataType: 'xml',
  beforeSend: function(xhr) {
    xhr.setRequestHeader("X-TrackerToken", "<KEY>")
  },
  data: '<story><story_type>feature</story_type><name>Fire torpedoes</name></story>',
  success: function() { alert('PUT completed'); }
});

but I am stumped on how to take my base64 encoded jpg and send it as if I had uploaded a file in a form.

Any ideas?

like image 464
latentflip Avatar asked Dec 08 '10 21:12

latentflip


2 Answers

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.

like image 111
flyandi Avatar answered Sep 22 '22 08:09

flyandi


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'));
like image 42
namitha gowda Avatar answered Sep 22 '22 08:09

namitha gowda