簡體   English   中英

如何在django中提供可下載的zip文件

[英]how to serve downloadable zip file in django

我瀏覽了django文檔,我發現這段代碼允許您將文件呈現為附件

dl = loader.get_template('files/foo.zip')
context = RequestContext(request)
response = HttpResponse(dl.render(context), content_type = 'application/force-download')
response['Content-Disposition'] = 'attachment; filename="%s"' % 'foo.zip'
return response

foo.zip文件是使用pythons zipfile.ZipFile()。writestr方法創建的

zip = zipfile.ZipFile('foo.zip', 'a', zipfile.ZIP_DEFLATED)
zipinfo = zipfile.ZipInfo('helloworld.txt', date_time=time.localtime(time.time()))
zipinfo.create_system = 1
zip.writestr(zipinfo, StringIO.StringIO('helloworld').getvalue())
zip.close()

但是當我嘗試上面的代碼來渲染文件時,我得到了這個錯誤

'utf8'編解碼器無法解碼位置10中的字節0x89:無效的起始字節

有關如何做到這一點的任何建議嗎?

我想你想要的是為人們提供下載文件。 如果是這樣,你不需要渲染文件,它不是模板,只需要使用Django的HttpResponse將其作為附件提供

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

對於二進制文件, FileResponse優先於HttpResponse 此外,以'rb'模式打開文件可防止UnicodeDecodeError

zip_file = open(path_to_file, 'rb')
return FileResponse(zip_file)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM