Changing filename in BlobBuilder to be passed as FormData on XHR

会有一股神秘感。 提交于 2019-11-30 16:03:24

问题


I'm currently trying to upload an ArrayBuffer to a server (which i can't change) that expects the file i'm uploading on a multipart/form-data format. The server extracts from the Content-Disposition part the filename that will be saved and under Content-type the MIME type which will be used when serving the file. Currently, i'm succesful on uploading the file with:

var xhr = new XMLHttpRequest();
var fdata = new FormData();
var bb;

if (WebKitBlobBuilder) {
    bb = new WebKitBlobBuilder();
} else if (MozBlobBuilder) {
    bb = new MozBlobBuilder();
} else if (BlobBuilder) {
    bb = new BlobBuilder();
}

bb.append(obj.array);

fdata.append('file', bb.getBlob("application/octet-stream"));

xhr.open("POST", url, true);
xhr.send(fdata);

But the headers are sent as the browser likes, on Chrome for example:

Content-Disposition: form-data; name="file"; filename="blob"
Content-Type: application/octet-stream;

I've contemplated saving it to a temporary file with FileWriter API and then upload it, but that just isn't right.

When answering, take into account:

  • The server can't be modified, nor i'm willing to select another server provider.
  • It must work at least on Firefox and Chrome (my app is alredy limited to those two browsers).

回答1:


Just solved it myself, thanks to a Chromium issue pointing me to the answer on w3c standard draft XMLHttpRequest. Basically i should change:

fdata.append('file', bb.getBlob("application/octet-stream"));

to:

fdata.append('file', bb.getBlob("application/octet-stream"), obj.filename);

And it gives the desired result.



来源:https://stackoverflow.com/questions/8495301/changing-filename-in-blobbuilder-to-be-passed-as-formdata-on-xhr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!