django - 如何在 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
是安全问题还是权限问题?
解决方案
经过大量研究,这是我发现的。
在 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 的方式提供。
推荐阅读
- webpack - Webpack 加载器在编译结束时发出文件
- nlp - (NLP, TextCNN) 为什么 in_channels 等于 torch.nn.Conv1d 中的嵌入大小?
- artificial-intelligence - 如何通过从以前的分布中学习来预测用户生成的分布
- java - 如果字符串包含连字符,则使用正则表达式验证第二个名称
- arrays - 将本地动态数组的长度设置为零会减少内存使用吗?
- python - SpaCy-nightly init fill-config 命令给出 ModuleNotFoundError
- c++ - 如何解决此代码中的分段错误?
- javascript - Jquery ui datepicker预选不是星期天的日期
- firebase - 有没有办法用firebase自动发送通知到flutter应用程序
- c - printf 给出分段错误?