Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading JavaScript generated image to Django

I have an image generated on the client side which I want to transfer to the server through a form. For example, let's say that I have a registration form in which the profile image is generated automatically by JavaScript, and I want to transfer that image to django.

What is the best way to transfer the image binary data to the server when user hit the submit button? what form field should I use?

thanks!

like image 706
Ronen Ness Avatar asked Jun 18 '13 16:06

Ronen Ness


1 Answers

Found an answer myself, here's the solution in case someone needs it:

In the client side, this is how you get the image from canvas and set it to a form field (a hidden char field):

var dataURL = document.getElementById('canvas_id').toDataURL("image/png");
document.getElementById('id_hidden_image_field').value = dataURL;

And in django side:

  1. add to the form a hidden field called 'hidden_image_field', which will be used to pass the data. this field is a simple CharField. you can add max_length limit to make sure image is in a reasonable size (note: not dimensions but actual size).

  2. to parse the image data:

    import re
    import base64
    dataUrlPattern = re.compile('data:image/(png|jpeg);base64,(.*)$')
    ImageData = request.POST.get('hidden_image_field')
    ImageData = dataUrlPattern.match(ImageData).group(2)
    
    # If none or len 0, means illegal image data
    if (ImageData == None or len(ImageData) == 0:
        # PRINT ERROR MESSAGE HERE
        pass
    
    # Decode the 64 bit string into 32 bit
    ImageData = base64.b64decode(ImageData)
    

and now ImageData contains the binary data, you can simply save to a file and it should work.

hope this helps.

like image 61
Ronen Ness Avatar answered Nov 08 '22 12:11

Ronen Ness