Search code examples
pythondjangoimagehttpresponse

read() image file with Python and send it to HttpResponse


I am trying to return an image to HttpResponse(image_data), but I get a page contain weird symbols. I can use PIL to .show() image perfectly from that path, but I want to display the image in browser instead of paint or an photo viewer app.

        image_data = open("media/hello.jpg", "rb").read()
        return HttpResponse(image_data, content_type="image")

weird symbols: ÿØÿá�Exif��II*������������ÿì�Ducky�����d��ÿî�Adobe�dÀ���ÿÛ�„�


Solution

  • Make use of FileResponse

    from django.http import FileResponse
    
    def send_file(response):
    
        img = open('media/hello.jpg', 'rb')
    
        response = FileResponse(img)
    
        return response