截图后粘贴或拖拽上传

在浏览器中使用截图工具截图后直接粘贴到页面上传,以及拖拽到页面标签区域上传

主要使用了粘贴(paste)事件,以及拖拽(drag)事件,其中拖拽时要禁用浏览器的默认将图片打开的行为

例子:

HTML部分:

    <div>
        截图后粘贴或拖拽到下框:
        <div id="upload" style="width: 800px; height: 600px; border: 1px solid red;">
        </div>
    </div>

js部分:

  1 <script>
  2     (function (mod) {
  3         if (typeof exports == "object" && typeof module == "object") // CommonJS
  4             module.exports = mod();
  5         else if (typeof define == "function" && define.amd) // AMD
  6             return define([], mod);
  7         else // Plain browser env
  8             window.UploadImage = mod();
  9     })(function () {
 10 
 11 
 12         function UploadImage(id, url, key) {
 13             this.element = document.getElementById(id);
 14             this.url = url; //后端处理图片的路径
 15             this.imgKey = key || "AreaImgKey"; //提到到后端的name
 16 
 17         }
 18         //粘贴图片事件
 19         UploadImage.prototype.paste = function (callback, formData) {
 20             var thatthat = this;
 21             this.element.addEventListener('paste', function (e) {//处理目标容器(id)的paste事件
 22 
 23                 if (e.clipboardData && e.clipboardData.items.length > 0 && e.clipboardData.items[0].type.indexOf('image') > -1) {
 24                     var that = this,
 25                     file = e.clipboardData.items[0].getAsFile();//读取e.clipboardData中的数据
 26 
 27                     dataReader(file, function (e) { //reader读取完成后,xhr上传
 28                         var fd = formData || (new FormData());
 29                         fd.append(thatthat.imgKey, this.result); // this.result得到图片的base64
 30 
 31                         xhRequest('POST', thatthat.url, fd, callback, that);
 32 
 33                     });
 34 
 35                 }
 36             }, false);
 37 
 38         };
 39 
 40         //拖拽事件
 41         UploadImage.prototype.drag = function (callback, formData) {
 42             var that = this;
 43             this.element.addEventListener('drop', function (e) {//处理目标容器(id)的drop事件
 44                 e.preventDefault(); //取消默认浏览器拖拽效果
 45                 var fileList = e.dataTransfer.files; //获取文件对象
 46                 //检测是否是拖拽文件到页面的操作
 47                 if (fileList.length == 0) {
 48                     return false;
 49                 }
 50                 //检测文件是不是图片
 51                 if (fileList[0].type.indexOf('image') === -1) {
 52                     console.log && console.log("您拖的不是图片!");
 53                     return false;
 54                 }
 55                 var fd = formData || (new FormData());
 56                 fd.append(that.imgKey, fileList[0]); //
 57                 xhRequest('POST', that.url, fd, callback, this);
 58 
 59             }, false);
 60         };
 61 
 62         //上传
 63         UploadImage.prototype.upload = function (callback, formData) {
 64             this.drag(callback, formData);
 65             this.paste(callback, formData);
 66         };
 67 
 68         preventDragDefault();
 69         //private
 70 
 71         function xhRequest(method, url, formData, callback, callbackContext) {
 72             var xhr = new XMLHttpRequest();
 73             xhr.open(method, url, true);
 74             xhr.onload = function () {
 75                 callback && callback.call(callbackContext || this, xhr);
 76             };
 77             xhr.send(formData || (new FormData()));
 78 
 79         }
 80 
 81         function preventDragDefault()//阻止浏览器默认将图片打开的行为
 82         {
 83             document.addEventListener("dragleave", preventDefault);//拖离
 84             document.addEventListener("drop", preventDefault);//拖后放
 85             document.addEventListener("dragenter", preventDefault);//拖进
 86             document.addEventListener("dragover", preventDefault);//拖来拖去
 87         }
 88 
 89         function preventDefault(e) {
 90             e.preventDefault();
 91         }
 92 
 93         function dataReader(file, callback) {
 94             var reader = new FileReader();
 95             reader.onload = callback;
 96             reader.readAsDataURL(file);//获取base64编码
 97         }
 98         return UploadImage;
 99     });
100 
101 </script>

调用:

<script>
    new UploadImage("upload", "UploadImage").upload(function (xhr) {
        var img = new Image();
        img.src = xhr.responseText;
        this.appendChild(img);
    });

</script>

后端保存图片部分代码:

        [HttpPost]
        public ActionResult UploadImage()
        {
            if (!System.IO.Directory.Exists(Server.MapPath("upload")))
            {
                System.IO.Directory.CreateDirectory(Server.MapPath("upload"));
            }
            if (Request.Files.Count == 0)
            {
                string strData = Request["AreaImgKey"].ToString(); //粘贴上传,取的base64编码
                Bitmap img = Base64StringToImage(strData);
                string imgName = "/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
                if (img != null)
                {
                    img.Save(Server.MapPath("upload") + imgName, System.Drawing.Imaging.ImageFormat.Jpeg);
                    return Content("upload" + imgName);
                }
            }
            else   //拖拽上传可直接拿到文件
            {
                string imgName = "/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Request.Files[0].FileName;
                Request.Files[0].SaveAs(Server.MapPath("upload") + imgName);
                return Content("upload" + imgName);
            }
            return Content("");
        }

        protected Bitmap Base64StringToImage(string strbase64)
        {
            try
            {
                byte[] arr = Convert.FromBase64String(strbase64.Split(',')[1]);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                ms.Close();
                return bmp;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

demo源码下载地址:链接:https://pan.baidu.com/s/1bMdl5saJruVy0d4DcFj6Bg 密码:iqui

posted @ 2018-09-09 22:05  赛跑的蜗牛  阅读(1204)  评论(0编辑  收藏  举报