【发布时间】:2015-07-06 07:45:10
【问题描述】:
我正在尝试让用户下载我生成的 xml 文件。
这是我的代码:
tree.write('output.xml', encoding="utf-16")
# Pathout is the path to the output.xml
xmlFile = open(pathout, 'r')
myfile = FileWrapper(xmlFile.read())
response = HttpResponse(myfile, content_type='application/xml')
response['Content-Disposition'] = 'attachment; filename='+filename
return response
当我尝试创建我的回复时,我得到了这个异常:
'\\'str\\' object has no attribute \\'read\\''
无法弄清楚我做错了什么。有什么想法吗?
编辑: 当我使用此代码时,我没有收到任何错误,但下载的文件是空的
tree.write('output.xml', encoding="utf-16")
xmlFile = open(pathout, 'r')
myfile = FileWrapper(xmlFile)
response = HttpResponse(myfile, content_type='application/xml')
response['Content-Disposition'] = 'attachment; filename='+filename
return response
【问题讨论】:
-
我在想,你真的要存储文件吗?你也可以使用 Django 模板来渲染它。
-
@Wtower 好问题但错误的解决方案 - 您不需要模板来呈现 xml,只需将其(以字符串形式)传递给
HttpResponse对象。 -
用户必须能够存储文件,只要它可以工作,我就不需要将它存储在服务器上:) @Wtower
-
@brunodesthuilliers 你是什么意思错误的解决方案?我发表了评论而不是答案,您的评论似乎没有回答。在Django中你无论如何都不必使用模板,这并不意味着它是实用的。
-
@Wtower 我的意思是,当您可以将 XML 直接传递给
HttpResponse对象时,使用 Django 模板来呈现已经格式良好的 XML 是没有用的。
标签: python django download attachment