显示上载(图像)文件的最简单方法? [英] Easiest way to display uploaded (image)file?

查看:70
本文介绍了显示上载(图像)文件的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试Django文件上传的第一次尝试,我目前需要的是一种向上传的用户显示上传的图像(png/jpg)的方法.

I'm trying to my first attempt at django file-uploading, and all i need at the moment is a way to display an uploaded image (png/jpg) to the user that uploaded.

无需将其保存在任何地方.

No need to save it anywhere.

我的views.py:(我正在使用django表单,顺便说一句)

My views.py: (i'm using django forms, btw)

if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        upFile = request.FILES['upFile']
        f={"upFile":upFile}
        return render_to_response('upload2.html', f)

并且我可以按预期使用以下命令在模板中显示文件的名称和大小{{upFile.name}}和{{upFile.size}}

And i can, as expected, display the name and size of my file in the template, using {{ upFile.name }} and {{ upFile.size }}

是否有一种方法可以将其加载/直接在呈现的模板中显示为"InMemoryUploadedFile",而无需进行文件保存?

Is there a way to load it/show it in the rendered template directly as an 'InMemoryUploadedFile', without going to effort of saving the files?

推荐答案

您可以像这样从图像数据中创建数据URI:

You can make a data URI out of the image data like this:

URI创建:

if form.is_valid():
    upFile = request.FILES['upFile']
    data = upFile.read()
    encoded = b64encode(data)
    mime = # the appropriate mimetype here, maybe "image/jpeg"
    mime = mime + ";" if mime else ";"
    f = {"upFile": "data:%sbase64,%s" % (mime, encoded)}
    return render_to_response('upload2.html', f)

然后在模板中使用它:

<img src="{{ upFile }}">

这篇关于显示上载(图像)文件的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆