Pergunta

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?

Foi útil?

Solução

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 }}">
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top