首页 > 解决方案 > 如何在 django 中提供图像?

问题描述

我有一个二进制字段来保存图像

    photograph = models.BinaryField(default=None)

在我的表单中,我保存图像

            photograph = cd['photograph'].file.getvalue(),
        )

在我看来

    f = open('my.jpeg', 'bw')
    myfile = File(f)
    myfile.write(student.photograph)
    filepath = os.path.abspath(os.path.realpath('my.jpeg'))
    context['urls'] = filepath
    return render(request, 'dashboard.html', context)

图像已保存到数据库,正在成功检索。 图片保存成功截图 我的模板

模板中的 HTML 呈现良好。如果我将 HTML 复制到本地文件中,则图像看起来很好。但是,当我使用 django 时,图像无法正确加载。 右键单击>复制图像地址给我这个:about:blank#blocked

是安全问题还是权限问题?

标签: django

解决方案


经过大量研究,这是我发现的。

在 HTML 中

<img src = "data/image:jpeg;base64, {{base64_string}}/>

在视野中

from django.http import urlsafe_b64encode
return render(request, 'template.html', {'base64_string' : urlsafe_b64encode(myobject.photograph)

这适用于开发。对于生产,我想静态文件可以以 django 的方式提供。


推荐阅读