工作正常的部分:
我已经提交了<form>
,其提交调用发出了ajax
请求。代码相同:
$.ajax({
type: 'POST',
url: '/uploaded_proto_file/',
data: formdata,
processData: false,
contentType: false,
success: function (data) {
console.log("in success")
console.log("data is --->"+data)
return;
},
error: function (data) {
console.log("in error")
return;
}
});
我可以在下面的功能中接收相同的电话。现在我需要发送一个文件(在我的文档结构中),需要在我的浏览器中自动下载。我根据这个answer
执行这个功能def uploaded_proto_file(request):
with open(
'/Users/metal/Documents/test_pb2.py','rb') as text_file:
response = HttpResponse(FileWrapper(text_file.getvalue()), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=test_pb2.py'
return response
上面的代码没有正常工作,所以我调试了它并在filewrapper
语句中发现了这个错误
现在我稍微更改了解决方案,但是响应中发回的文件没有自动下载,它在控制台中打印(因为我在ajax函数中的成功块有console.log(数据))
更改解决方案:
with open(
'/Users/metal/Documents/test_pb2.py','rb') as text_file:
response = HttpResponse(text_file, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=test_pb2.py'
return response
正如您在上面所看到的,我删除了FileWrapper
并且至少能够将文件发送回ajax
请求。但问题仍然存在,因为文件没有自动下载。
P.S。 :我还尝试在不同的模式下打开file
,例如&#39; r&#39;&#39; rb&#39;。
任何帮助将不胜感激!
答案 0 :(得分:0)
您无法将文件返回到ajax请求并期望将其下载。你需要的是分成几个步骤:
.click()
),然后再次将其删除。有点像this example