vue粘贴上传

HTML部分

<div class="paste-content" v-if="uploadConfig.pasteUpload && uploadConfig.fileList.length < uploadConfig.limit">
      <div contenteditable="true"
        ref="pasteContentRef"
        @focus="contentEditFocus($event)"
        @input="contentEditFocus($event)"
        @blur="contentEditBlur($event)"
      >
        点击此处,粘贴上传
      </div>
    </div>

<el-upload ref="upload"></el-upload>
export default {
  data() {
    return {
      uploadConfig: {
        pasteUpload: true, // 是否显示粘贴上传
        limit: 5, // 最大允许上传个数
        fileList: [],
      }
    }
  },
  mounted() {
    const { pasteUpload } = this.uploadConfig
    if (pasteUpload) {
      this.pasteEvent()
    }
  },
  methods: {
    /**
     * 将base64转换为blob
     */
     dataURLtoBlob (dataurl) {
      let arr = dataurl.split(',');
      let array = arr[0].match(/:(.*?);/);
      let mime = (array && array.length > 1 ? array[1] : type) || type;
      // 去掉url的头,并转化为byte
      let bytes = window.atob(arr[1]);
      // 处理异常,将ascii码小于0的转换为大于0
      let ab = new ArrayBuffer(bytes.length);
      // 生成视图(直接针对内存):8位无符号整数,长度1个字节
      let ia = new Uint8Array(ab);
      for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      return new Blob([ab], {
        type: mime
      })
    },
    /**
     * 将blob转换为file
     */
     blobToFile  (theBlob, fileName = 'name.jpeg') {
      theBlob.lastModifiedDate = new Date();
      theBlob.name = `${new Date().getTime()}.png`; // 上传的文件名
      return theBlob;
    },
    /**调用element的上传方法 需要把base64转换成file上传**/
    uploadImgFromPaste(file, type, isChrome) {
      const dataFile = this.dataURLtoBlob(file);
      const blobFile = this.blobToFile(dataFile);
      const uploadRef = this.$refs.upload
      uploadRef?.handleStart(blobFile);
      setTimeout(()=>{
        uploadRef?.submit();
        // 提交后,走el-upload组件的上传方法
      })
    },
    contentEditFocus($event) {
      $event.target.innerText = "按Ctrl+V 将图片粘贴至此处";
    },
    contentEditBlur($event) {
      $event.target.innerText = "点击此处,粘贴上传";
    },
    pasteEvent() {
      const _this = this;
      this.$refs.pasteContentRef?.addEventListener('paste', function (event) {
        // 粘贴事件 https://www.jb51.net/article/80657.htm
        let isChrome = false;
        if (event.clipboardData || event.originalEvent) {
          // not for ie11  某些chrome版本使用的是event.originalEvent
          const clipData = (event.clipboardData || event.originalEvent.clipboardData);
          if (clipData.items) {
            // for chrome
            // firefox 火狐浏览器没有实现粘贴上传,有兼容问题
            let items = clipData.items,
              len = items.length,
              blob = null;
              isChrome = true;
            //items.length
            //粘贴纯文本,那么len=1,如果粘贴网页图片,len=2, items[0].type = 'text/plain', items[1].type = 'image/*'
            //使用截图工具粘贴图片,len=1, items[0].type = 'image/png'
            //粘贴纯文本+HTML,len=2, items[0].type = 'text/plain', items[1].type = 'text/html'
            //阻止默认行为即不让剪贴板内容在div中显示出来
            event.preventDefault();
            //在items里找粘贴的image,据上面分析,需要循环
            for (let i = 0; i < len; i++) {
              if (items[i].type.indexOf("image") !== -1) {
                // 获取图片内容
                blob = items[i].getAsFile();
              }
            }
            if (blob !== null) {
              let reader = new FileReader();
              reader.onload = function (event) {
                // event.target.result 为图片的Base64编码字符串
                let base64_str = event.target.result
                //可以在这里写上传逻辑 直接将base64编码的字符串上传(可以尝试传入blob对象,要看后台能否解析)
                _this.uploadImgFromPaste(base64_str, 'paste', isChrome);
              }
              reader.readAsDataURL(blob);
            }
          }
        }
      })
    }
  }
}
<style scoped>
.paste-content {
  background-color: #fff;
  border: 1px dashed #409eff;
  border-radius: 6px;
  box-sizing: border-box;
  // height: 50px;
  display: inline-block;
  margin-bottom: 10px;
  padding: 0 8px;
  line-height: 30px;
  cursor: pointer;
}
</style>

 

使用input获取文件格式,可上传图片与其他格式文件

<el-input @paste.native="onPasteUpload($event)" value="按Ctrl+V 将文件粘贴至此处上传" />
onPasteUpload(event) {
            // 粘贴上传
      const { items } = event.clipboardData || {};
      let file = null;
      if (items && items.length) {
        // 检索剪切板items
        if (items[0].kind == "file") {
          file = items[0].getAsFile();
        } else {
          this.$message.error("粘贴内容不是文件内容,请重新复制后粘贴");
        }
      }
      if (!file) {
        return;
      }
            const uploadRef = this.$refs.upload;
            uploadRef?.handleStart(file);
            setTimeout(() => {
                uploadRef?.submit();
            });
    },

 

posted @ 2022-09-16 10:02  日升月恒  阅读(280)  评论(0编辑  收藏  举报