通过django下载图像

时间:2011-09-05 08:32:25

标签: django download

我尝试从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文件有效。为什么呢?

1 个答案:

答案 0 :(得分:1)

您可能需要以二进制模式打开文件:

wrapper = FileWrapper(open(filepath, 'rb'))