【问题标题】:Paste image into rich text (like gmail)将图像粘贴到富文本中(如 gmail)
【发布时间】:2011-06-18 01:25:10
【问题描述】:

我希望能够从剪贴板复制图像,特别是屏幕截图,并将它们直接粘贴到富文本编辑器中,和/或上传该文件。我们只使用 chrome,所以它只适用于 chrome。

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

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

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

【问题讨论】:

  • stackoverflow.com/questions/490908/… Firefox(可能还有 Chrome)将图像粘贴为 <image> 标签,并将数据 URI 作为 href。我不知道 Gmail 是如何做到的。可能是event.clipboardData

标签: javascript google-chrome clipboard


【解决方案1】:

我相信 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 上传图片,而不是直接将其嵌入为数据 URL。在 Google 或 SO 上搜索拖放文件上传应该会揭示如何实现这一点。

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

希望这会有所帮助!

【讨论】:

  • 嗨,感谢它的工作 chrome 和 firefox 的好代码。但是当我尝试运行时,即它不起作用。你对此有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 2010-09-30
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
相关资源
最近更新 更多