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
onDataTransferItemList
: parameter 1 is not of typeFile
.
尝试 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:
Chrome >=38:
火狐:
Blob
传递 Blob
可能是正确的并且在 Firefox 中有效:
var file = new File([new Blob()], "image.png", {type:"image/png"});
火狐:
Chrome <38:
Chrome >=38:
- 问:那么如何从
Blob
生成File
呢?
注意:在@apsillers 提醒我更新 Google Chrome 后,我添加了更多屏幕截图。
最佳答案
File 构造函数(以及 Blob 构造函数)接受一个部分数组。部分不必是 DOMString。它也可以是 Blob、文件或类型化数组。您可以像这样轻松地从 Blob 构建文件:
new File([blob], "filename")
关于javascript - 如何从 Blob 创建文件对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27251953/