如果能够在 Stack Exchange 上粘贴图像而不是干扰文件对话框,那将非常方便。类似的功能在这里实现了(是?),但是仅适用于 Webkit 浏览器 https://meta.stackexchange.com/a/233874/209994.
我正在开发执行此操作的用户脚本 https://stackapps.com/q/4999/28478。有趣的是我从未获得过file https://developer.mozilla.org/en/docs/Web/API/File(与原始图像数据不同)在 Webkit 浏览器中来自剪贴板,而在 Firefox 中则有效。
火狐解决方案:
div.addEventListener('paste', function(event){
//I'm actually not sure what should event.originalEvent be. I copypasted this
var items = (event.clipboardData || event.originalEvent.clipboardData);
console.log("paste", items);
//Try to get a file and handle it as Blob/File
var files = items.items || items.files;
if(files.length>0) {
//Being lazy I just pick first file
var file = files[0];
//handle the File object
_this.processFile(file);
event.preventDefault();
event.cancelBubble = true;
return false;
}
});
在 Chrome 没有像 Firefox 那样好的文档(我指的是 MDN)之前,我尝试检查正在发生的事情。我复制了一个文件并将其粘贴到 Google chrome (v39) 中。这就是我在DataTransfer
控制台中的对象:
作为参考,这是 Firefox 中的同一事件:
另外两个数组,items
and types
Firefox 实现中不存在。当我复制文本或原始图像数据时,Chrome 将其表示为DataTransferItem
。我发现最好忽略这些:
//Being lazy I just pick first file
var file = files[0];
//GOOGLE CHROME
if(file.getAsFile) {
console.log("DataTransferItem:", file);
//HTML or text will be handled by contenteditable div
if(file.type!="text/plain" && file.type!="text/html") {
//handle the File object
_this.processFile(file.getAsFile());
}
}
else
...
到目前为止,除了text/plain
or text/html
。对于这些,.getAsFile
回报null
.
我发现 google chrome 模型有点令人困惑。它为您提供了有关原始数据(文本/原始图像)的更多信息,这些信息只能使用内容可编辑的 div 进行访问,但对我来说不是很清楚。