javascript - 如何从 Blob 创建文件对象?

标签 javascript fileapi

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

复制事件

我的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);
}

chrome 中的错误:

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

尝试 new File(Blob blob, DOMString name)

我在 Google Chrome 中试过这个,according to the current specification :

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

这里的问题是,谷歌浏览器不太遵守规范。

Uncaught TypeError: Failed to construct File: Illegal constructor

在这种情况下,Firefox 也没有:

The method parameter is missing or invalid.

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

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

二进制数据

我试图避免 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

您可以在控制台中尝试:

Chrome <38:
google chrome is retarded Chrome >=38:
google chrome not retarded anymore 火狐: firefox firebug fileAPI

Blob

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

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

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

  • 问:那么如何从 Blob 生成 File 呢?

注意:在@apsillers 提醒我更新 Google Chrome 后,我添加了更多屏幕截图。

最佳答案

File 构造函数(以及 Blob 构造函数)接受一个部分数组。部分不必是 DOMString。它也可以是 Blob、文件或类型化数组。您可以像这样轻松地从 Blob 构建文件:

new File([blob], "filename")

关于javascript - 如何从 Blob 创建文件对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27251953/

相关文章:

javascript - 脚本 5007 : Unable to get value of the property '0' : object is null or undefined

cordova - window.resolveLocalFileSystemURL与window.requestFileSystem

javascript - <img>重载时宽度返回0

javascript - EmberJS-在 Handlebars 模板内添加动态数据属性

javascript - 如何从模板添加 SVG g 元素?

javascript - Ember 异步计算属性返回未定义

javascript - html5文件api,将用户选择的目录存储在sessionStorage中?

javascript - 创建一个 FileList 并将其复制到一个文件输入

javascript - 根据另一个添加一个处理程序?

javascript - 验证从WebApp发送到Web Service的数据的有效性