我发出一个jqueryajaxpost请求,并将数据传递到Django框架中的后端python代码。我需要返回的zip文件作为httpresponse,这应该是自动下载的浏览器。在
object_body = request.body.decode('utf-8')
loaded_json = json.loads(object_body)
json_obj = ast.literal_eval(str(loaded_json))
zip_file_path = importexport.download(json_obj,user)
zip_filename = os.path.basename(zip_file_path)
with open(zip_file_path, 'rb') as zip:
response = HttpResponse(zip.read(), content_type = 'application/x-zip')
response['Content-Disposition'] = 'attachment; filename=' + zip_filename
return response
您不想使用
.read()
,只需使用filestream
所以,请尝试这样的方法如果您有下载URL(将文件放入媒体根目录),您只需编写带有
download
属性的a
标记,然后按下面的代码片段中所述单击“下载”,它将自动下载文件,而无需重定向。在<a href="https://github.com/vaibhavmule/vaibhavmule.github.io/archive/master.zip" download>Download</a>
;一种解决方案:
将zip文件放入MEDIA_ROOT,并重定向到其url。