图片上传插件ImgUploadJS:用HTML5 File API 实现截图粘贴上传、拖拽

2019-01-28 15:49:11刘景俊
一 . 背景及效果

当前互联网上传文件最多的就是图片文件了,但是传统web图片的截图上传需要:截图保存->选择路径->保存后再点击上传->选择路径->上传->插入。
图片文件上传也需要:选择路径再->上传->插入,步骤繁杂,互联网体验为王,如果支持截图粘贴上传、拖拽上传将大大提升体验。
当前知乎和github对现代浏览器均支持这两种特性,闲来无事就学习实现了一下,今天就说一说这个1kb插件实现什么功能,怎么使用和原理。
首先看一下插效果:
截图后直接粘贴上传。

拖拽上传

http网络


二.使用示例
直接调用:
XML/HTML Code复制内容到剪贴板
  1. <div id="box" style="width: 800px; height: 400px; border: 1px solid;" contenteditable="true"></div>     <script type="text/javascript" src="UploadImage.js"></script>    
  2. new UploadImage("box", "UploadHandler.ashx").upload(function (xhr) {//上传完成后的回调     var img = new Image();    
  3. img.src = xhr.responseText;     this.appendChild(img);    
  4. }); 


AMD/CMD

XML/HTML Code复制内容到剪贴板
  1. <div id="box" style="width: 800px; height: 400px; border: 1px solid;" contenteditable="true"></div>     <script type="text/javascript" src="require.js"></script>    
  2. <script>     require(['UploadImage'], function (UploadImage) {    
  3. new UploadImage("box", "UploadHandler.ashx").upload(function (xhr) {//上传完成后的回调     var img = new Image();    
  4. img.src = xhr.responseText;     this.appendChild(img);    
  5. });     })    
  6. </script>