我尝试从django网站下载图片。我是这样做的:
def file_download(request, filename):
from django.core.servers.basehttp import FileWrapper
import mimetypes
import settings
import os
filepath = os.path.join(settings.MEDIA_ROOT, filename)
wrapper = FileWrapper(open(filepath))
content_type = mimetypes.guess_type(filepath)[0]
response = HttpResponse(wrapper, mimetype='content_type')
response['Content-Disposition'] = "attachment; filename=%s" % filename
return response
但是,它不适用于图像(我尝试jpg文件),但对txt文件有效。为什么呢?
答案 0 :(得分:1)
您可能需要以二进制模式打开文件:
wrapper = FileWrapper(open(filepath, 'rb'))