問題描述
我目前正在嘗試將 ArrayBuffer 上傳到服務器(我無法更改),該服務器期望我上傳的文件采用 multipart/form-data 格式.服務器從 Content-Disposition
部分中提取將被保存的 filename
并在 Content-type
下提取服務時將使用的 MIME 類型文件.目前,我已成功上傳文件:
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);
但標頭是按照瀏覽器的喜好發送的,例如在 Chrome 上:
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;
我曾考慮使用 FileWriter API 將其保存到臨時文件中,然后上傳,但這是不對的.
I've contemplated saving it to a temporary file with FileWriter API and then upload it, but that just isn't right.
回答時要考慮:
- 服務器無法修改,我也不愿意選擇其他服務器提供商.
- 它必須至少在 Firefox 和 Chrome 上運行(我的應用已經僅限于這兩種瀏覽器).
推薦答案
剛剛自己解決了,感謝 Chromium 問題指出 w3c 標準草案的答案 XMLHttpRequest.基本上我應該改變:
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"));
到:
fdata.append('file', bb.getBlob("application/octet-stream"), obj.filename);
它給出了想要的結果.
這篇關于在 BlobBuilder 中更改文件名以作為 XHR 上的 FormData 傳遞的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!