问题描述
我正在尝试导出我的网页数据并将其下载为excel文件。但即使回复成功,下载也不会开始。
I am trying to export my web page data and download it as excel file. but the download does not start even the response return succeed.
$.ajax({
type: "POST",
url: _url,
contentType: 'multipart/form-data;boundary=SzB12x',
data: json,
});
responseText是这样的:
The responseText something like this:
?PKJ;˚FXL /主题/ theme1.xmlYOo6 ,[RN; 6#-kJH:OC {0 X72
MZ 杜@(6B:M
{| ^ 0t@ *w $ !0I [ n i ' iH g , | J ?!? hRh h ?r& ߶L ߶S v@ ? # ? } Жt% hR t + ? u{ނ 0K oy 9OTWywkAͯ $ b $b F 6* [ U
PK�J;Fxl/theme/theme1.xml�YOo�6����,[r��n;v��i����#-�kJH:�oC{0X7�2
��mZ���d��u@�(٦b:M����
�����{|��^�0t@��*"w$�!0I�[�՚n�i��'����iH� g�,��|�J�!���hRh�h��?r&�L ���߶S��v@���#���"���}��Жt%�hR�t"������+��������u{ނ��0K���oy�9OTWywkAͯ����F�� 6*�����[���U���
我认为它的文件但我无法下载!!
I think its the file but I cant download it!!
请帮忙吗?
谢谢!
推荐答案
我遇到了同样的问题并成功解决了它。我的用例就是这样。
I faced the same issue and successfully solved it. My use-case is this.
- 将JSON数据发布到服务器并接收excel文件。
- 那个excel文件是在运行中创建并作为对客户的回复返回。
代码:
$("#my-button").on("click", function() {
// Data to post
data = {
ids: [1, 2, 3, 4, 5]
};
// Use XMLHttpRequest instead of Jquery $ajax
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
var a;
if (xhttp.readyState === 4 && xhttp.status === 200) {
// Trick for making downloadable link
a = document.createElement('a');
a.href = window.URL.createObjectURL(xhttp.response);
// Give filename you wish to download
a.download = "test-file.xls";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
};
// Post data to URL which handles post request
xhttp.open("POST", excelDownloadUrl);
xhttp.setRequestHeader("Content-Type", "application/json");
// You should set responseType as blob for binary responses
xhttp.responseType = 'blob';
xhttp.send(JSON.stringify(data));
});
上面的代码片段正在执行以下操作
The above snippet is just doing following
- 使用XMLHttpRequest将数组作为JSON发布到服务器
- 在将内容作为blob(二进制)获取之后,我们创建了一个可下载的URL并将其附加到不可见的a链接然后单击它。
这里我们需要在服务器端仔细设置一些东西。我在Python Django HttpResponse中设置了几个标题。如果您使用其他编程语言,则需要相应地设置它们。
Here we need to carefully set few things at the server side. I set few headers in Python Django HttpResponse. You need to set them accordingly if you are use other programming languages.
# In python django code
response = HttpResponse(file_content, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
由于我在这里下载xls(excel),我将contentType调整为高于1。您需要根据文件类型进行设置。
Since I download xls(excel) here, I adjusted contentType to above one. You need to set it according to your file type.
这篇关于通过jquery ajax post下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!