我有一个在客户端生成的图像,我想通过一个表单传输到服务器。例如,假设我有一个注册表单,通过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方面:
将一个隐藏的字段添加到表单中,该隐藏字段称为hidden_image_field,用于传递数据。这个字段是一个简单的CharField。您可以添加max_length限制,以确保图像的尺寸合理(注意:不是尺寸,而是实际尺寸)。
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 = repile('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
发布评论