将 HTML5 Canvas 转换为要上传的文件?

2022-01-17 00:00:00 base64 jquery javascript html5-canvas

标准的 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:

  1. 从画布创建图像(如您所做的那样).
  2. 在新页面上显示该图像.
  3. 让用户右键单击并保存到他们的本地驱动器.
  4. 然后他们可以使用您的文件输入元素上传新创建的文件.

或者,您可以使用 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.

相关文章