如何在python中发送httpresponse附件中的zip文件

2024-10-04 03:26:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我发出一个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

Tags: 数据pathdjango代码框架jsonobjobject
3条回答

您不想使用.read(),只需使用filestream所以,请尝试这样的方法

def report_generate(request):
    filename = "mysample.zip"
    f = open(filename, "rb")
    response = HttpResponse(f, content_type='application/x-zip')
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename
    return response

如果您有下载URL(将文件放入媒体根目录),您只需编写带有download属性的a标记,然后按下面的代码片段中所述单击“下载”,它将自动下载文件,而无需重定向。在

<a href="https://github.com/vaibhavmule/vaibhavmule.github.io/archive/master.zip" download>Download</a>

和13;
和13;

一种解决方案:

将zip文件放入MEDIA_ROOT,并重定向到其url。

相关问题 更多 >