Javascript Input type="file" 设置base64图片数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33297858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Input type="file" set base64 image data
提问by VB_
I have a canvas and retrieve image data from it with help of canvas.toDataURL('image/png')
.
我有一个画布,并在canvas.toDataURL('image/png')
.
Problem:<input type="file" />
wants filepath as value
instead of base64 data.
问题:<input type="file" />
想要文件路径value
而不是 base64 数据。
Question:How to send base64 image data to server with help of <input type="file" />
WITHOUT saving them to local file system?
问题:如何在<input type="file" />
不将它们保存到本地文件系统的帮助下将 base64 图像数据发送到服务器?
My workarounds:Tried hidden input <input type="file" />
, but server requires filename property
我的解决方法:尝试隐藏输入<input type="file" />
,但服务器需要文件名属性
Maybe that's possible to overcome this with XmlHttpRequest?
也许可以用 XmlHttpRequest 克服这个问题?
回答by Charlie
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
元素的名称。
<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:
如果您想为此使用XMLHttpRequest
,以下是一个示例:
//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);
回答by Natural Lam
You can use FileReader, check examples here: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
您可以使用 FileReader,在此处查看示例:https: //developer.mozilla.org/en-US/docs/Using_files_from_web_applications