Loading generated javascript image in Django

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

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

thanks!

+6
source share
1 answer

I found the answer myself, here is a solution in case someone needs it:

On the client side, you will receive an image from the canvas and set it in the form field (hidden char field):

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

And on the django side:

  • Add a hidden field called "hidden_image_field" to the form, which will be used to transfer data. This field is a simple CharField. you can add a max_length constraint to make sure the image has a reasonable size (note: not the dimensions, but the actual size).

  • to analyze 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 binary data, you can just save the file and it should work.

hope this helps.

+8
source

Source: https://habr.com/ru/post/947572/


All Articles