我有以下用於通過django管理文件下載的代碼。由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字節的大小。 (該文件大於此)
好點!然而,我已經評論了印刷品並且仍然具有類似的行爲(事實上,我已經添加了印刷品以嘗試瞭解印刷品)。看到我的更新 – luc 2012-01-05 11:46:28
是的,但是什麼證明你的回答只是迭代一次?畢竟,響應使用你的文件包裝來完成它的內容。 – 2012-01-05 15:54:07