python - 使用 Python read() 图像文件并将其发送到 HttpResponse

标签 python django image httpresponse

我试图将图像返回到 HttpResponse(image_data),但我得到一个包含奇怪符号的页面。 我可以使用 PIL 从该路径完美地显示 () 图像,但我想在浏览器中显示图像,而不是绘画或照片查看器应用程序。

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

奇怪的符号:ÿØÿá�Exif��II*������������ÿì�Ducky�����d��ÿî� Adob​​e�dÀ���ÿÛ�„�

最佳答案

利用FileResponse

from django.http import FileResponse

def send_file(response):

    img = open('media/hello.jpg', 'rb')

    response = FileResponse(img)

    return response

关于python - 使用 Python read() 图像文件并将其发送到 HttpResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65787023/

相关文章:

Django 导入导出 : only export

python - 如何将 Django 模型数据导出到 CSV 文件

jQuery 旋转图像(使用旋转插件)每次单击旋转 +/-90 度

jquery - BXSlider CSS代码不滑动

python - 运行时错误: Working outside of application context with Celery and Flask in Python

python - 在测试套件中运行单元测试(每个测试作为单独的测试脚本)

python - 在管理员中从 TabularInline 中删除标题

c# - 试图将 byte[] 转换为 jpg 文件

python - 为什么 github3.py 两次要求第二个身份验证因素?

python - 如何在 Python ClientForm 中设置一个不存在的字段?