当前 互联网 上 传文件 最多的就是图片文件了,但是传统web图片的截图上传需要:截图保存->选择路径->保存后再点击上传->选择路径->上传->插入。
图片文件上传也需要:选择路径再->上传->插入,步骤繁杂,互联网体验为王,如果支持截图粘贴上传、拖拽上传将大大 提升 体验。
当前 知乎 和g IT h ub 对现代浏览器均支持这两种特性,闲来无事就学习实现了一下,今天就说一说这个1kb插件实现什么功能,怎么使用和原理。
首先看一下插效果:
截图后直接粘贴上传。
拖拽上传
http网络
二.使用示例
直接调用:
XM L/HT ML Code 复制内容到剪贴板
< div &nbs p; id = "box" style = "width: 800px; h ei ght: 400px; border: 1px solid;" contenteditable = "true" > </ div > < script ty PE = "text/javascript" src = "UploadImage.js" > </ script > new UploadImage("box", "UploadHandler.ashx").upload(function (x hr ) {//上传完成后的回调 VAR img = new Image(); img.src = xhr .responseText; this.appendChild(img); });
am D/CMD
XML/HTML Code 复制内容到剪贴板
< div id = "box" style = "width: 800px; height: 400px; border: 1px solid;" contenteditable = "true" > </ div > < script type = "text/javascript" src = "require.js" > </ script > < script > require(['UploadImage'], function (UploadImage) { new UploadImage("box", "UploadHandler.ashx").upload(function (xhr) {//上传完成后的回调 var img = new Image(); img.src = xhr .responseText; this.appendChild(img); }); }) </ script >
三.浏览器支持
当前版本只支持以下,浏览器,后期可能会支持更多浏览器。
•IE11
•Ch rom e
•FireFox
•Safari(未测式,理论 应该 支持)
四.原理及 源 码
1.粘贴上传
处理目标容器(id)的paste事件,读取e.clipboardData中的数据,如果是图片进行以下处理:
用H5 File API(FileReader)获取文件的base64代码,并构建FormData异步上传。
2.拖拽上传
处理目标容器(id)的drop事件,读取e.data transfer .files(H5 File API: FileList)中的数据,如果是图片并构建FormData异步上传。
以下是初版本代码,比较 简单 。不再赘述。
部份核心代码
XML/HTML Code 复制内容到剪贴板
function UploadImage(id, url, key) { this.element = document .getElementById(id); this.url = url; // 后端 处理图片的路径 this.imgKey = key || "PasteAre ai mgKey"; //提到到后端的name } UploadImage. PR ototype.paste = function (callback, formData) { var t hat that = this ; this.element.addEventListener('paste', function (e) {//处理目标容器(id)的paste事件 if (e.clipboardData && e.clipboardData.items[0].type.indexOf('image') > -1) { var that = this , reader = new FileReader(); file = e.clipboardData.items[0].getAsFile();//读取e.clipboardData中的数据:Blob对象 reader.onload = function (e) { //reader读取完成后,xhr上传 var xhr = new XMLHttpRequest(), fd = formData || (new FormData());; xhr.open('POST', thatthat.url, true); xhr.onload = function () { callback.call(that, xhr); } fd.append(thatthat.imgKey, this.result); // this.result得到图片的base64 xhr.send(fd); } reader.readAsDataURL(file);//获取base64编码 } }, false); }
总结
以上是 为你收集整理的 图片上传插件ImgUploadJS:用HTML5 File API 实现截图粘贴上传、拖拽上传 全部内容,希望文章能够帮你解决 图片上传插件ImgUploadJS:用HTML5 File API 实现截图粘贴上传、拖拽上传 所遇到的问题。
如果觉得 网站内容还不错, 推荐好友。
查看更多关于图片上传插件ImgUploadJS:用HTML5 File API 实现截图粘贴上传、拖拽上传的详细内容...