問題描述
我知道 jQuery 的 ajax 方法無法處理下載,我不想添加 jQuery 插件來執行此操作.
I'm aware that jQuery's ajax method cannot handle downloads, and I do not want to add a jQuery plugin to do this.
我想知道如何使用 XMLHttpRequest 發送 POST 數據來下載文件.
I want to know how to send POST data with XMLHttpRequest to download a file.
這是我嘗試過的:
var postData = new FormData();
postData.append('cells', JSON.stringify(output));
var xhr = new XMLHttpRequest();
xhr.open('POST', '/export/', true);
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
console.log(e);
console.log(xhr);
}
xhr.send(postData);
我正在使用 Django,并且文件似乎已成功發送回客戶端.在 Chrome 的網絡選項卡中,我可以在預覽選項卡中看到亂碼(這是我所期望的).但我想發回一個 zip 文件,而不是 zip 文件的文本表示.這是 Django 后端:
I'm working with Django, and the file appears to be sending back to the client successfully. In the network tab in Chrome, I can see gibberish in the preview tab (which I expect). But I want to send back a zip file, not a text representation of the zip file. Here's the Django back end:
wrapper = FileWrapper(tmp_file)
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = "attachment; filename=export.zip"
response['Content-Length'] = tmp_file.tell()
return response
我已經搜索了好幾個小時,但沒有找到關于如何使用 XMLHttpRequests 執行此操作的適當示例.我不想使用 POST 操作創建正確的 html 表單,因為表單數據相當大,并且是動態創建的.
I've searched this for hours now without finding a proper example on how to do this with XMLHttpRequests. I don't want to create a proper html form with a POST action because the form data is rather large, and dynamically created.
上面的代碼有問題嗎?我錯過了什么?我只是不知道如何實際將數據作為下載發送到客戶端.
Is there something wrong with the above code? Something I'm missing? I just don't know how to actually send the data to the client as a download.
推薦答案
UPDATE:自從引入 Blob API.詳情請參考 Steven 的回答.
UPDATE: this answer is not accurate anymore since the introduction of Blob API. Please refer to Steven's answer for details.
原始答案:
XHR 請求不會觸發文件下載.我找不到明確的要求,但 W3C doc on XMLHttpRequest 沒有描述任何特殊對 content-disposition=attachment 響應的反應
XHR request will not trigger file download. I can't find explicit requirement, but W3C doc on XMLHttpRequest doesn't describe any special reaction on content-disposition=attachment responses either
如果不是 POST 請求,您可以通過 window.open()
在單獨的選項卡中下載文件.這里建議使用帶有 target=_blank的隱藏表單代碼>
You could download file by window.open()
in separate tab, if it was not POST request. Here it was suggested to use a hidden form with target=_blank
這篇關于使用 XMLHttpRequest 提示文件下載的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!