标准的 HTML 文件上传工作如下:
The standard HTML file upload works as follows:
<g:form method="post" accept-charset="utf-8" enctype="multipart/form-data"
name="form" url="someurl">
<input type="file" name="file" id="file" />
</form>
在我的情况下,我将图像加载到 html5 画布中,并希望将其作为文件提交到服务器.我能做到:
In my case I loaded an image into a html5 canvas and want to submit it as a file to the server. I can do:
var canvas; // some canvas with an image
var url = canvas.toDataURL();
这给了我一个 base64 格式的图像/png.
This gives me a image/png as base64.
如何将 base64 图像发送到服务器,就像使用输入类型文件一样?
问题是base64文件和文件的类型不一样,在input type="file"里面.
The problem is that the base64 file is not of the same type as the file, which is inside the input type="file".
能否以某种方式转换服务器类型相同的base64?
出于安全原因,您不能直接设置文件输入元素的值.
For security reasons, you can't set the value of a file-input element directly.
如果你想使用文件输入元素:
If you want to use a file-input element:
或者,您可以使用 Ajax 发布画布数据:
Alternatively, you can use Ajax to POST the canvas data:
你问的是 blob:
var blobBin = atob(dataURL.split(',')[1]);
var array = [];
for(var i = 0; i < blobBin.length; i++) {
array.push(blobBin.charCodeAt(i));
}
var file=new Blob([new Uint8Array(array)], {type: 'image/png'});
var formdata = new FormData();
formdata.append("myNewFileName", file);
$.ajax({
url: "uploadFile.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
}).done(function(respond){
alert(respond);
});
注意:最新的浏览器一般都支持 blob.
Note: blob is generally supported in the latest browsers.
这篇关于将 HTML5 Canvas 转换为要上传的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!