【发布时间】:2012-01-05 10:41:58
【问题描述】:
我有以下代码用于通过 django 管理文件下载。
def serve_file(request, id):
file = models.X.objects.get(id=id).file #FileField
file.open('rb')
wrapper = FileWrapper(file)
mt = mimetypes.guess_type(file.name)[0]
response = HttpResponse(wrapper, content_type=mt)
import unicodedata, os.path
filename = unicodedata.normalize('NFKD', os.path.basename(file.name)).encode("utf8",'ignore')
filename = filename.replace(' ', '-') #Avoid browser to ignore any char after the space
response['Content-Length'] = file.size
response['Content-Disposition'] = 'attachment; filename={0}'.format(filename)
#print response
return response
不幸的是,我的浏览器在下载时得到一个空文件。
打印出来的响应似乎是正确的:
Content-Length: 3906
Content-Type: text/plain
Content-Disposition: attachment; filename=toto.txt
blah blah ....
我有类似的代码运行正常。我看不出有什么问题。有什么想法吗?
PS:我已经测试了here 提出的解决方案并得到了相同的行为
更新:
将wrapper = FileWrapper(file) 替换为wrapper = file.read() 似乎可以解决问题
更新:如果我评论 print response,我会遇到类似的问题:。该文件是空的。唯一的区别:FF 检测到 20 字节大小。 (文件比这个大)
【问题讨论】: