【发布时间】:2013-10-27 20:47:18
【问题描述】:
我正在查看 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:无效起始字节
关于如何正确执行此操作的任何建议?
【问题讨论】:
-
为什么要渲染一个 .zip 文件的模板?您确定这是提供文件的文档中的内容吗?
-
你好,我正在尝试将其呈现为附件。据我所知,您可以在 django 响应中指定要吐出的内容类型,类似于上面的代码
-
您确定 render 是您想要的正确词吗?我宁愿认为您只是想提供它供人们下载,对吗?
-
如果你是这样定义的,好吧。底线是使文件可在 django 中下载。
标签: python django file web render