最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTML editor and pasting images from Word - Stack Overflow

programmeradmin6浏览0评论

We have made a very simple html editor (contenteditable="true") and users can paste images copied from other web pages, but if the user copy an image from word, word will paste the src as file://temp/someimg.jpg and the browser will not load the image.

<img src="file://..../.jgp">

But if I run the web page on my dev puter (http://127.0.0.1) and do the same, word will paste the image src as "data:image/jpeg;base64....."

Is there some way I can make word paste the base64 encoded picture to the editor always and not only the file:// location?

We have made a very simple html editor (contenteditable="true") and users can paste images copied from other web pages, but if the user copy an image from word, word will paste the src as file://temp/someimg.jpg and the browser will not load the image.

<img src="file://..../.jgp">

But if I run the web page on my dev puter (http://127.0.0.1) and do the same, word will paste the image src as "data:image/jpeg;base64....."

Is there some way I can make word paste the base64 encoded picture to the editor always and not only the file:// location?

Share Improve this question edited Jun 10, 2017 at 6:03 YowE3K 24k7 gold badges27 silver badges45 bronze badges asked Jun 10, 2017 at 4:54 Mr ZachMr Zach 5154 silver badges19 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

You will need to handle the paste event and read the clipboard for image content. Please find the prototype in below snippet (tested in google chrome) which demonstrates the same.

// create paste event listener
window.addEventListener("paste", pasteHandler);

// handle paste events
function pasteHandler(e) {
  if (e.clipboardData) {
    var items = e.clipboardData.items;
    if (items) {
      for (var i in items) { // iterate through clipbord items
        var item = items[i];
        if (item.kind == "file") {  //image is a file
        
          // create image source
          var blob = item.getAsFile();
          var URLObj = window.URL || window.webkitURL;
          var source = URLObj.createObjectURL(blob);
          var pastedImage = new Image();
          pastedImage.src = source;
          
          // add it in editor
          document.getElementById("editor").innerHTML = document.getElementById("editor").innerHTML + pastedImage.outerHTML;
        }
      }
    }
  }
}
#editor{
  min-width: 400px;
  min-height: 250px;
  border: solid;
  border-width: thin;
  padding: 10px;
}
<div id="editor" contenteditable=true>Copy an image from word<br/>Press Ctrl+v to paste it here <br/></div>

发布评论

评论列表(0)

  1. 暂无评论