Django - 通过ajax请求提供文件
我有一个使用extjs的ajax功能,它可以把一个表单发送到服务器,服务器会返回一个可以下载的文件,并且带有正确的头信息。这个文件可以通过浏览器的正常下载窗口进行下载。不过,ajax请求的成功回调函数并没有被触发,ajax请求一直在等待响应,处于挂起状态。
有没有办法告诉ajax函数,文件是否已经从服务器正确发送了呢?
exportLayer = function(node_id){
Ext.Ajax.request({
method: "GET",
form: "exportForm",
url: "/basqui/layer/shapefile/export/" + node_id + "/",
success: function(r){
html = Ext.decode(r.responseText).html
Ext.get('pageContent').update(html);
},
});
}
服务器端:
temp = tempfile.TemporaryFile()
zip = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
shapefileBase = os.path.splitext(dstFile)[0]
shapefileName = os.path.splitext(layer.filename)[0]
for fName in os.listdir(dstDir):
zip.write(os.path.join(dstDir, fName), fName)
zip.close()
#delete temporary files
shutil.rmtree(dstDir)
#return the zip to user
f = FileWrapper(temp)
response = StreamingHttpResponse(f, content_type="application/zip")
response['Content-Disposition'] = "attachment; filename=" + shapefileName + fileExt_dic[format]
response['Content-Length'] = temp.tell()
temp.seek(0)
return response
1 个回答
1
你不能通过Jquery的Ajax来下载文件。因为这样的话,浏览器根本收不到响应。我之前也遇到过这个问题,后来我这样解决了:
$(".dwnBtn").click(function(){
let url = "{% url 'the url'%}"
$.post(url, function(data)
{
console.log(data);
location.replace(url);
});
}) 这样做会让浏览器重新加载页面,然后就能下载你的文件了。