将JavaScript生成的图像上传到Django

编程入门 行业动态 更新时间:2024-10-28 18:25:02
本文介绍了将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方面:

  • 将一个隐藏的字段添加到表单中,该隐藏字段称为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

    本文发布于:2023-10-05 12:22:48,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1467368.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:图像   JavaScript   Django

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!