将JavaScript生成的图像上传到Django [英] Uploading JavaScript generated image to Django

查看:133
本文介绍了将JavaScript生成的图像上传到Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在客户端生成的图像,我想通过一个表单传输到服务器。例如,假设我有一个注册表单,通过JavaScript自动生成配置文件图像,我想将该图像传输到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?

谢谢!

推荐答案

找到一个答案我自己,这里的解决方案,如果有人需要它:

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;

在django方面:


  1. 将一个隐藏的字段添加到表单中,该隐藏字段称为hidden_​​image_field,用于传递数据。这个字段是一个简单的CharField。您可以添加max_length限制,以确保图像的尺寸合理(注意:不是尺寸,而是实际尺寸)。

  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).

来解析图像数据: p>

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)


现在ImageData包含二进制数据,您可以简单地保存到一个文件中,它应该可以工作。

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

希望这有帮助。

这篇关于将JavaScript生成的图像上传到Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆