Easiest way to display uploaded (image)file?

匆匆过客 提交于 2021-02-19 06:27:30

问题


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.

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)

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

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?


回答1:


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

URI creation borrowed from http://djangosnippets.org/snippets/2516/:

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)

Then use it in the template:

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


来源:https://stackoverflow.com/questions/12751183/easiest-way-to-display-uploaded-imagefile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!