输入类型=“文件”设置base64图像数据

编程入门 行业动态 更新时间:2024-10-27 16:30:41
本文介绍了输入类型=“文件”设置base64图像数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个画布,并借助于 canvas.toDataURL('image / png')从中检索图像数据。

问题: < input type =file/> 希望filepath为 code>代替base64数据。

问题: 如何在< input type =file/> 无需将它们保存到本地文件系统中? strong>我的解决方法:尝试隐藏输入< input type =file/> ,但服务器需要文件名属性

也许可以用XmlHttpRequest来解决这个问题吗? 您的表单中隐藏的输入元素。 (注意 type )

< input type =hiddenname =myHiddenField> ;

在提交前将数据附加到元素的值。

var imageData = canvas.toDataURL('image / png'); document.getElementsByName(myHiddenField)[0] .setAttribute(value,imageData);

更新

如果您的服务器要求在提交的数据中使用参数filename,然后将该字符串作为 input 元素的名称。

< input type =hiddenname =文件名/>

这将欺骗表单提交包含在其中的filename参数的数据。 p>

如果您想为此使用 XMLHttpRequest ,下面是一个示例:

//准备要发送的数据 var imageData = canvas.toDataURL('image / png'); var params =文件名=+ imageData; //发起请求 var httpRequest = new XMLHttpRequest(); httpRequest.open('POST','test.php',true); //发送适当的头文件 httpRequest.setRequestHeader(Content-type,application / x-www-form-urlencoded); httpRequest.setRequestHeader(Content-length,params.length); httpRequest.setRequestHeader(Connection,close); //发送你的数据 httpRequest.send(params);

I have a canvas and retrieve image data from it with help of canvas.toDataURL('image/png').

Problem: <input type="file" /> wants filepath as value instead of base64 data.

Question: How to send base64 image data to server with help of <input type="file" /> WITHOUT saving them to local file system?

My workarounds: Tried hidden input <input type="file" />, but server requires filename property

Maybe that's possible to overcome this with XmlHttpRequest?

解决方案

Just create a hidden input element in your form. (notice the type)

<input type="hidden" name="myHiddenField">

Attach your data to the value of the element before submitting.

var imageData = canvas.toDataURL('image/png'); document.getElementsByName("myHiddenField")[0].setAttribute("value", imageData);

UPDATE

If your server demands to have the parameter "filename" in the submitted data, then include that string as the name of the input element.

<input type="hidden" name="filename"/>

This will trick the form to submit your data with the "filename" parameter included in it.

If you want to use XMLHttpRequest for this, following is a sample:

//Prepare data to be sent var imageData = canvas.toDataURL('image/png'); var params = "filename=" + imageData; //Initiate the request var httpRequest = new XMLHttpRequest(); httpRequest.open('POST', 'test.php', true); //Send proper headers httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); httpRequest.setRequestHeader("Content-length", params.length); httpRequest.setRequestHeader("Connection", "close"); //Send your data httpRequest.send(params);

更多推荐

输入类型=“文件”设置base64图像数据

本文发布于:2023-10-11 23:58:39,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图像   类型   文件   数据

发布评论

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

>www.elefans.com

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