Javascript 如何从 Blob 创建 File 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27251953/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:55:46  来源:igfitidea点击:

How to create File object from Blob?

javascriptfileapi

提问by Tomá? Zato - Reinstate Monica

DataTransferItemList.addallows you to override copy operation in javascript. It, however, only accepts Fileobject.

DataTransferItemList.add允许您覆盖 javascript 中的复制操作。然而,它只接受File对象。

Copy event

复制事件

The code in my copyevent:

我的copy活动中的代码:

var items = (event.clipboardData || event.originalEvent.clipboardData);
var files = items.items || items.files;

if(files) {
  var blob = Blob.fromDataURL(_this.editor.selection.getSelectedImage().toDataURL("image/png"));
  files.add(blob);
}

The error in chrome:

铬中的错误:

Uncaught TypeError: Failed to execute addon DataTransferItemList: parameter 1 is not of type File.

Uncaught TypeError: Failed to execute addon DataTransferItemList: parameter 1 is not type File

Trying the new File(Blob blob, DOMString name)

尝试 new File(Blob blob, DOMString name)

In Google Chrome I tried this, according to the current specification:

在谷歌浏览器中,我根据当前规范尝试了这个:

var blob = Blob.fromDataURL(_this.editor.selection.getSelectedImage().toDataURL("image/png"));  
var file = new File(blob, "image.png");

Problem here is, that Google Chrome doesn't stick to specifications very much.

这里的问题是,谷歌浏览器并不太符合规范。

Uncaught TypeError: Failed to construct File: Illegal constructor

未捕获的类型错误:无法构造File:非法构造函数

Neither does Firefox in this case:

在这种情况下,Firefox 也不会:

The method parameter is missing or invalid.

方法参数丢失或无效。

Trying the new File([Mixed blobParts], DOMString name, BlobPropertyBag options)

尝试 new File([Mixed blobParts], DOMString name, BlobPropertyBag options)

Solution suggested by @apsillers doesn't work too. This is non stadard method used (but useless) in both Firefoxand Chrome.

@apsillers 建议的解决方案也不起作用。这是在FirefoxChrome 中使用(但无用)的非标准方法。

Binary data

二进制数据

I tried to avoid blob, but the file constructor failed anyway:

我试图避免 blob,但无论如何文件构造函数都失败了:

  //Canvas to binary
  var data = atob(   //atob (array to binary) converts base64 string to binary string
    _this.editor.selection.getSelectedImage()  //Canvas
    .toDataURL("image/png")                    //Base64 URI
    .split(',')[1]                             //Base64 code
  );
  var file = new File([data], "image.png", {type:"image/png"}); //ERROR

You can try that in console:

您可以在控制台中尝试:

Chrome <38:
google chrome is retardedChrome >=38:
google chrome not retarded anymoreFirefox: firefox firebug fileAPI

铬 <38
谷歌浏览器迟钝铬 >=38
谷歌浏览器不再迟钝火狐firefox firebug fileAPI

Blob

斑点

Passing Blobis probably correct and works in Firefox:

传递Blob可能是正确的并且在 Firefox 中有效:

var file = new File([new Blob()], "image.png", {type:"image/png"});

Firefox:
Firefox firebug
Chrome <38:
google chrome is retarded
Chrome >=38:
google chrome not retarded anymore

火狐:
火狐萤火虫
铬 <38
谷歌浏览器迟钝
铬 >=38
谷歌浏览器不再迟钝

  • Q:So how can I make Filefrom Blob?
  • 问:那么,怎样才能让我FileBlob

Note: I added more screenshots after @apsillers reminded me to update Google Chrome.

注意:@apsillers 提醒我更新谷歌浏览器后,我添加了更多屏幕截图。

回答by pwnall

The File constructor (as well as the Blob constructor) takes an array of parts. A part doesn't have to be a DOMString. It can also be a Blob, File, or a typed array. You can easily build a File out of a Blob like this:

File 构造函数(以及 Blob 构造函数)采用部件数组。一部分不必是 DOMString。它也可以是 Blob、文件或类型化数组。您可以轻松地从 Blob 中构建文件,如下所示:

new File([blob], "filename")

new File([blob], "filename")

Please refrain from stating that browsers don't implement the spec or that the spec is useless if you don't take the time to understand the spec process or the spec itself.

如果您不花时间了解规范流程或规范本身,请不要说浏览器没有实现规范或规范是无用的。

回答by Arttu Pakarinen

this works with me, from canvas to File [or Blob], with filename!

这对我有用,从画布到文件 [或 Blob],文件名!

var dataUrl = canvas.toDataURL('image/jpeg');
var bytes = dataUrl.split(',')[0].indexOf('base64') >= 0 ?
          atob(dataUrl.split(',')[1]) :
          (<any>window).unescape(dataUrl.split(',')[1]);
var mime = dataUrl.split(',')[0].split(':')[1].split(';')[0];
var max = bytes.length;
var ia = new Uint8Array(max);
for (var i = 0; i < max; i++) {
  ia[i] = bytes.charCodeAt(i);
}

var newImageFileFromCanvas = new File([ia], 'fileName.jpg', { type: mime });

Or if you want a blob

或者如果你想要一个 blob

var blob = new Blob([ia], { type: mime });

回答by Hari Prasanna Addanki

This was the complete syntax which I had to use to convert a blob into a file, which I later had to save to a folder using my server.

这是我必须用来将 blob 转换为文件的完整语法,后来我不得不使用我的服务器将其保存到一个文件夹中。

var file = new File([blob], "my_image.png",{type:"image/png", lastModified:new Date()})