Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome WebKitBlobBuilder doesn't append data

I'm implementing some file upload feature through ajax request. I'd like to be able to send multiple files in one ajax call, so i decided to use FormData.

I tried to append my binary data string directly to the FormData (and it works), but the Content-Disposition doesn't have a filename attribute: Content-Disposition: form-data; name="file1"

w3c says that i need to append a blob object to the formdata to have that attribute (or to be able to set it with the 3rd attribute of FormData.append())

I wrote the following code:

function uploadAsBinary() {
    var xhr = new XMLHttpRequest();
    var fd = new FormData();

    window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
    var bb = new window.BlobBuilder();
    bb.append("this is my binary content");
    var blob = bb.getBlob("text/plain"); 

    fd.append("file1", blob, "file1");

    xhr.open("POST", "/mb/0/", false);
    xhr.send(fd);
}

It works perfectly fine with firefox, but with google chrome (v16 and v17), the request payload is a formdata without content in it:

------WebKitFormBoundaryVkgESMAGtmPMlPZ7
Content-Disposition: form-data; name="file1"; filename="file1"
Content-Type: text/plain


------WebKitFormBoundaryVkgESMAGtmPMlPZ7--

I've also tried to fill the blob through an ArrayBuffer, same result. I've been surfing the web for 2 days now, i've found no answer. I've found an open issue on android (http://code.google.com/p/android/issues/detail?id=22441) but it seems quite dead.

Is this a real chrome issue ? Does someone have a clue about this, or should i open an issue on chromium tracker ?

Thx for your help !

like image 598
Sebastien Avatar asked Nov 13 '22 08:11

Sebastien


1 Answers

For anyone looking for a solution here, the problem is the switch to Blob() rather than BlobBuilder() as explained here

BlobBuilder():

window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder ||
                 window.MozBlobBuilder || window.MSBlobBuilder;
window.URL = window.URL || window.webkitURL;

var bb = new BlobBuilder();
bb.append('body { color: red; }');
var blob = bb.getBlob('text/css');

var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = window.URL.createObjectURL(blob);

document.body.appendChild(link);

Blob():

window.URL = window.URL || window.webkitURL;

var blob = new Blob(['body { color: red; }'], {type: 'text/css'});

var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = window.URL.createObjectURL(blob);
document.body.appendChild(link);
like image 94
corylulu Avatar answered Nov 16 '22 04:11

corylulu