问题描述
我希望能够从剪贴板复制图片,特别是截图,并将其直接粘贴到富文本编辑器中,和/或上传该文件。我们只使用chrome,因此它只能用于chrome。
I want to be able to copy an image from clipboard, specifically screenshots, and paste them right into a rich text editor, and/or have that file uploaded. We only use chrome so it only has to work for chrome.
http://gmailblog.blogspot.com/2011/06/pasting-images-into-messages-just-got.html
有谁知道这是否新的Gmail功能是什么JavaScript的Id能够实现自己?还是有任何其他的见解?
Does anyone know if this new gmail feature is something javascript that Id be able to implement myself? Or any other insight into this?
推荐答案
我相信Na7coldwater是正确的。正在使用 event.clipboardData
。请参阅以下概念验证:
I believe Na7coldwater is correct. The event.clipboardData
is being utilised. Please see the following proof of concept:
<html>
<body>
<div id="rte" contenteditable="true" style="height: 100%; width: 100%; outline: 0; overflow: auto"></div>
<script type="text/javascript">
document.getElementById("rte").focus();
document.body.addEventListener("paste", function(e) {
for (var i = 0; i < e.clipboardData.items.length; i++) {
if (e.clipboardData.items[i].kind == "file" && e.clipboardData.items[i].type == "image/png") {
// get the blob
var imageFile = e.clipboardData.items[i].getAsFile();
// read the blob as a data URL
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
// create an image
var image = document.createElement("IMG");
image.src = this.result;
// insert the image
var range = window.getSelection().getRangeAt(0);
range.insertNode(image);
range.collapse(false);
// set the selection to after the image
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
};
// TODO: Error Handling!
// fileReader.onerror = ...
fileReader.readAsDataURL(imageFile);
// prevent the default paste action
e.preventDefault();
// only paste 1 image at a time
break;
}
}
});
</script>
</body>
Gmail通过 XMLHttpRequest
,而不是直接将其作为数据URL嵌入。在Google或SO上搜索拖拽& drop file uploads应该揭示如何实现这一点。
Gmail uploads the image via XMLHttpRequest
instead of embedding it directly as a data URL. A search on Google or SO for drag & drop file uploads should reveal how this can be achieved.
请记住,这只是一个概念证明。不包括错误处理和浏览器/功能检测代码。
Please bare in mind that this is just a proof of concept. Error handling and browser/feature detection code is not included.
希望这有助于!
这篇关于将图片粘贴到富文本(如Gmail)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!