如果能够在 Stack Exchange 上将图像粘贴到此处而不是插手文件对话框,那将会非常方便。类似的功能是(是?)在这里实现,但是only for Webkit browsers .
我正在开发 userscript that does that .有趣的是,我从来没有完成 file (不同于原始图像数据)来自 Webkit 浏览器中的剪贴板,而在 Firefox 中它可以工作。
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
和 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
或 text/html
之外,我从未想过得到任何其他东西。对于这些,.getAsFile
返回 null
。
我发现 google chrome 模型有点令人困惑。它为您提供了有关原始数据(文本/原始图像)的更多信息,这些信息只能使用内容可编辑的 div 进行访问,但我不是很清楚。
最佳答案
我们的魔法酱汁是:
$('body').bind('paste', handlepaste);
handlepaste
与您的非常相似,因此对于 Chrome 应该适合您。
不幸的是,上述对于 FF 完全失败,我们不愿意在任何地方添加 contenteditable
(特别是考虑到它必须才能工作并且我们不想抢走焦点)。
关于javascript - 如何在 webkit 浏览器中访问粘贴的文件? (如谷歌浏览器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27262428/