输入类型=“文件”设置base64图像数据 [英] Input type="file" set base64 image data

查看:123
本文介绍了输入类型=“文件”设置base64图像数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



问题: 如何在<$ $的帮助下将base64图像数据发送到服务器c $ c>< 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图像数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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