ChanDon
ChanDon

Reputation: 401

download images through django

I try to download an image from my django website. I do it like this:

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

However, it doesn't work for images (I tries jpg files), but do work for txt files. Why?

Upvotes: 1

Views: 1514

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

Probably you need to open the file in binary mode:

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

Upvotes: 1

Related Questions