Reputation: 139
I want Django to display an image when accessed. For example, I want to display only the image as a response, such as when accessing the image below. And I want to do the URL as a normal URL without using .jpeg or .png.
Sample:
But now, no matter what method you try, it doesn't work.
from django.http import HttpResponse
import os
from django.core.files import File
import codecs
def image(request):
file_name = os.path.join(
os.path.dirname(__file__),
'12.jpg'
)
try:
with open(file_name, "rb") as f:
a = f.read()
return HttpResponse(a, content_type="image/jpeg")
except IOError:
red = Image.new('RGBA', (1, 1), (255, 0, 0, 0))
response = HttpResponse(content_type="image/jpeg")
red.save(response, "JPEG")
return response
urlpatterns = [
url('image', image)
]
With the above code, the following error occurs.
'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
Upvotes: 1
Views: 232
Reputation: 139
The cause was my own middleware. There was no problem if I commented out. Thanks for those who have comments and those who have answered.
Upvotes: 0
Reputation: 51948
Simply use FileResponse
:
from django.http import FileResponse
def image(response):
img = open('path/to/12.jpg', 'rb')
response = FileResponse(img)
return response
Upvotes: 1