将图像粘贴到富文本中(如gmail)

时间:2011-06-18 01:25:10

标签: javascript google-chrome clipboard

我希望能够从剪贴板复制图像,特别是屏幕截图,然后将它们粘贴到富文本编辑器中,和/或上传该文件。我们只使用chrome,因此只需要使用chrome。

http://gmailblog.blogspot.com/2011/06/pasting-images-into-messages-just-got.html

  

现在,当您运行最新版本的Google Chrome时,您也可以直接从剪贴板粘贴图片。因此,如果您从网络或其他电子邮件中复制图像,则可以将其粘贴到邮件中。

有谁知道这个新的gmail功能是否能够自己实现的javascript?或者对此有何见解?

1 个答案:

答案 0 :(得分:20)

我相信Na7coldwater是正确的。正在使用event.clipboardData。请参阅以下概念证明:

<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上传图片,而不是直接将其作为数据网址嵌入。在Google或SO上进行搜索以进行拖动和搜索删除文件上传应该揭示如何实现这一目标。

请记住,这只是一个概念证明。不包括错误处理和浏览器/功能检测代码。

希望这有帮助!