Python Django-通过ajax请求服务文件
我有一个extjsajax函数,它向服务器发送一个表单,服务器返回一个文件以下载正确的头。可以使用浏览器的普通文件下载窗口下载文件。但是,ajax请求的成功回调函数不会被触发,ajax正在不确定地等待响应 有没有办法告诉ajax函数文件是否正确地从服务器发送Python Django-通过ajax请求服务文件,python,ajax,django,Python,Ajax,Django,我有一个extjsajax函数,它向服务器发送一个表单,服务器返回一个文件以下载正确的头。可以使用浏览器的普通文件下载窗口下载文件。但是,ajax请求的成功回调函数不会被触发,ajax正在不确定地等待响应 有没有办法告诉ajax函数文件是否正确地从服务器发送 exportLayer = function(node_id){ Ext.Ajax.request({ method: "GET", form: "exportForm", url: "/ba
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
不能使用Jquery Ajax下载。响应将无法到达浏览器。我曾经遇到过这个问题,我通过这样做解决了它:
$(".dwnBtn").click(function(){
let url = "{% url 'the url'%}"
$.post(url, function(data)
{
console.log(data);
location.replace(url);
});
})
这将使浏览器重新加载,然后下载您的文件。您可以从ajax或xhr请求将编码的二进制数据(base64或其他)返回到浏览器,然后使用javascript开始下载。请看我的回答: