简体   繁体   English

django打开一个zip文件供用户下载

[英]django open a zip file for user to download

Django 1.7, Python 3.4, windows apache 2.4.12 + wsgi Django 1.7,Python 3.4,Windows Apache 2.4.12 + wsgi

In my program, I generate some csv files and put them in a zip file. 在我的程序中,我生成了一些csv文件,并将它们放在zip文件中。 I would like to let the user download the zip file, either force download (after file is generated and render response) or a click of button (after display result, user has to click a button to download.) 我想让用户下载zip文件,或者强制下载(在生成文件并呈现响应之后),或者单击按钮(在显示结果之后,用户必须单击按钮进行下载)。

Currently I am forcing them to download once the zip file is generated on the server. 当前,一旦服务器上生成了zip文件,我就强迫他们下载。

I have referenced the following links and come up with my code below. 我引用了以下链接,并在下面提出了我的代码。 But it is always give me this error "'charmap' codec can't decode byte 0x8d in position 80: character maps to " I tried to set it with utf-8 and ascii, and similar errors will be given. 但这总是给我这个错误“字符映射编解码器无法解码位置80的字节0x8d:字符映射为”我试图用utf-8和ascii进行设置,并且会给出类似的错误。

referenced links: 参考链接:

Anyone know why am I getting this error and how to get this to work? 有人知道我为什么会收到此错误以及如何使其正常工作吗?

Thank you very much! 非常感谢你!

zip_filename = time.strftime("%Y%m%d") + ".zip"
with zipfile.ZipFile(zip_filename, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
    for s in sql_request:
        // generate csv files
        zf.write(csv_file)

// close zf

zip_file = open(zip_filename, 'r')
response = HttpResponse(zip_file, content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename="%s"' % 'foo.zip'
return response

如果您使用的是Windows,则可能需要更改open行以包含b标志

zip_file = open(zip_filename, 'rb')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM