Uploading JavaScript generated image to Django

后端 未结 1 1065
暗喜
暗喜 2021-02-04 18:34

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

相关标签:
1条回答
  • 2021-02-04 19:28

    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.

    0 讨论(0)
提交回复
热议问题