B
B
blackbb2016-10-29 12:10:46
Django
blackbb, 2016-10-29 12:10:46

How to process base64 form data in Django?

The site has a form for creating a model, it has a filefield. I'm trying to display photos and delete them before sending them to the server. everything works, but here's the question, how to process base64 strings on the server side? Or can anyone suggest a simpler solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-10-29
@blackbb

First, if you do not plan to work with ancient browsers that do not support FileReader, then it is easier to use it:

var fileField = document.getElementById('image');
var preview = document.getElementById('preview');
fileField.addEventListener('change', function(event) {
    var reader = new FileReader();
    reader.onload = function(event) {
        preview.setAttribute('src', event.target.result);
    }
    reader.readAsDataURL(event.target.files[0]);
}, false);

Secondly, if we encode the image in base64 before sending, then decoding it on the server side is elementary.
For Python2:
with open("image.png", "wb") as fh:
    fh.write(request.POST['image'].decode('base64'))

For Python3:
import base64
with open("image.png", "wb") as fh:
    fh.write(base64.decodestring(request.POST['image']))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question