el-upload+复制粘贴+批量进度条+压缩上传图片

html部分
<template>
  <!-- 为了第一次截屏,粘贴在对应组件上 -->
  <div id="editable" contenteditable="true"></div>
  <div id="upload_box">
    <el-upload ref="uploadFiles" v-model:file-list="fileList" :class="[del ? 'uploadDelectPosition' : '']"
      :action="UploadImg" list-type="picture-card" :on-preview="handlePreview" :before-upload="beforeAvatarUpload"
      :on-remove="handleRemove" :on-success="handleSuccess" :limit="limits" :on-change="handleChange" multiple
      :http-request="selectPicUpload">
      <span v-if="videoFlag">上传中...</span>
      <el-icon v-if="!videoFlag">
        <Plus />
      </el-icon>
    </el-upload>
  </div>
</template>
js代码部分
<script>
/**上传图片压缩 */
import * as imageConversion from "image-conversion";
/**提示框 */
import { ElMessage } from "element-plus";
/**接口地址 */
import apiUrl from "@/Utils/Config.js";
import CryptoTools from '@/Utils/CryptoTools.js'
export default {
  props: {
    limits: {
      type: Number,
      default: 2,
    },
    del: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      /**图片上传路径 */
      UploadImg: apiUrl.UploadUrl,
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      imgUrls: [],
      /**进度条的进度, */
      videoUploadPercent: 0,
      /**是否显示进度条 */
      videoFlag: false,
    };
  },
  methods: {
    beforeAvatarUpload(rawFile) {
      if (rawFile.type != "image/jpeg" && rawFile.type != "image/png") {
        ElMessage.error("只能上传jpg与png格式");
        return false;
      }
      return new Promise((resolve) => {
        imageConversion.compress(rawFile, 0.4).then((res) => {
          resolve(res);
        });
      });
    },
    handleChange(file, fileList) {
      this.videoFlag = true;
      if (file.status == "success") {
        this.videoFlag = false;
      }
    },
    /**自定义图片上传 */
    selectPicUpload(obj) {
      var _that = this;
      // let fd = new FormData();
      let rawFile = obj.file;
      console.log(rawFile);
      if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
        ElMessage.error("只能上传jpg与png格式");
        return false;
      }
      new Promise((resolve) => {
        imageConversion.compress(rawFile, 0.4).then((res) => {
          resolve(res);
        });
      }).then((res) => {
        // fd.append("file", res, "file.png");
        // _that.$http.UploadImage(fd, (file) => {
        //   _that.videoFlag = false;
        //   _that.videoUploadPercent = 0;
        //   _that.imgUrls.push(file.rows);
        //   _that.$emit("ImgId", _that.imgUrls);
        // });
        CryptoTools.OSSUpload(res, (data => {
          if (data.Success) {
            _that.videoFlag = false;
            _that.videoUploadPercent = 0;
            _that.imgUrls.push(data.rows.url);
            _that.$emit("ImgId", _that.imgUrls);
          } else { }
        }))
      });
    },
    handleSuccess(file, fileList) {
      this.videoFlag = false;
      this.videoUploadPercent = 0;
      this.imgUrls.push(file.url);
      console.log(this.imgUrls);
      this.$emit("ImgId", this.imgUrls);
    },
    handleRemove(file, fileList) {
      let index = this.imgUrls.indexOf(
        file.response?.Data.Item2.Url || file.url
      );
      this.imgUrls.splice(index, 1);
      this.$emit("ImgId", this.imgUrls);
    },
    handlePreview(file) {
      this.previewVisible = true;
      this.previewPath = file.response.data.url;
    },
    /**图片回显 */
    GetImage(val) {
      // console.log(val);
      this.imgUrls = val;
      let arr = [];
      val?.forEach((item, i) => {
        arr.push({ name: i + ".jpg", url: item });
      });
      this.fileList = arr;
      console.log(this.fileList);
    },
    //进度条
    uploadVideoProcess(event, file, fileList) {
    },

    /**粘贴上传实现 */
    // 监听截屏对应事件粘贴方法
    listenerPaste() {
      let _this = this;
      window.addEventListener("paste", function (event) {
        // event.preventDefault();
        event.stopPropagation();
        // 为了截屏时,粘贴在当前的组件,第一次必须促发一次
        (function () {
          document.getElementById("editable").click();
        })();
        _this.paste_img(event);
      });
    },
    // 粘贴方法
    paste_img(e) {
      let _this = this;
      if (e.clipboardData.items) {
        let ele = e.clipboardData.items;
        // 只能为图片的时候才可以粘贴图片
        for (var i = 0; i < ele.length; ++i) {
          if (ele[i].kind == "file" && ele[i].type.indexOf("image/") !== -1) {
            var fileObj = ele[i].getAsFile(); //获取图片信息

            window.URL = window.URL || window.webkitURL;
            var blobUrl = window.URL.createObjectURL(fileObj);
            fileObj.src = blobUrl;
            // console.log(blobUrl);
            this.convertImgToBase64(blobUrl, function (base64Img) {
              let blobData = _this.dataURLtoBlob(base64Img);
              // let formdata = new FormData(); // new一个formdata对象
              let _filename = new Date().getTime() + ".jpg"; // 修改文件名
              // formdata.append("file_upload", blobData, _filename); // key值, 二进制类型文件,文件名
              CryptoTools.OSSUpload(blobData, (data => {
                if (data.Success) {
                  let fileCopy = {
                    ...fileObj,
                    response: JSON.parse(JSON.stringify(data.rows)),
                    percentage: 100,
                    raw: fileObj,
                    status: "success",
                    name: fileObj.name,
                    size: fileObj.size,
                    type: fileObj.type,
                  };
                  _this.fileList.push({
                    name: data.rows.url,
                    url: data.rows.url,
                  });
                  _this.handleSuccess(data.rows, fileCopy, [fileCopy]);
                  window.removeEventListener("paste", _this.paste_img);
                }
              }))

              // _this.$http.UploadImage(formdata, (res) => {
              //   console.log("res", res);
              //   // 格式化文件对象,与el-upload的uploadSuccess方法返回文件对象对应
              //   let fileCopy = {
              //     ...fileObj,
              //     response: JSON.parse(JSON.stringify(res)),
              //     percentage: 100,
              //     raw: fileObj,
              //     status: "success",
              //     name: fileObj.name,
              //     size: fileObj.size,
              //     type: fileObj.type,
              //   };
              //   console.log(res);
              //   _this.fileList.push({
              //     name: res.rows,
              //     url: res.rows,
              //   });
              //   _this.handleSuccess(res, fileCopy, [fileCopy]);
              //   window.removeEventListener("paste", _this.paste_img);
              // });
            });
          }
        }
      } else {
        console.log("non-chrome");
      }
    },
    // base64Img
    convertImgToBase64(url, callback, outputFormat) {
      var canvas = document.createElement("CANVAS"),
        ctx = canvas.getContext("2d"),
        img = new Image();
      img.crossOrigin = "Anonymous";
      img.onload = function () {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL(outputFormat || "image/png");
        // console.log("dataURL", dataURL);
        callback.call(this, dataURL);
        canvas = null;
      };
      img.src = url;
      // console.log(" img.src", img.src);
    },

    //将base64转换为blob
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
  },
  mounted() {
    this.listenerPaste();
  },
};
</script>
样式部分
<style lang="less" scoped>
// el-upload删除按钮进行定位让其显示出来
.uploadDelectPosition {

  /deep/ .el-upload-list__item-actions {
    // 放大图标进行隐藏
    .el-upload-list__item-preview {
      // display: none;
      position: absolute;
      top: calc(50% - 10px);
      left: calc(50% - 40px);
    }

    .el-upload-list__item-delete {
      position: absolute;
      top: calc(50% - 10px);
      left: calc(-50% - 55px);
    }
  }
}

/deep/ .el-upload {
  position: relative;

  .elProgress {
    svg {
      position: absolute;
      top: calc(50%);
      left: calc(43%);
      transform: translate(-60px, -55px);
      width: 120px !important;
      height: 120px !important;
    }

    span {
      position: relative;
      left: -4px;
      top: 3px;
    }
  }

}
</style>
使用
<!-- <UploadImg :limits="''" del @ImgId="getImageList" /> -->
<!-- limits 上传图片数目限制  :limits="''"表示无限制 默认限制是 2  -->
<!-- del 是否携带删除按钮 默认是不带删除的 -->
完整代码
<template>
  <!-- 为了第一次截屏,粘贴在对应组件上 -->
  <div id="editable" contenteditable="true"></div>
  <div id="upload_box">
    <el-upload ref="uploadFiles" v-model:file-list="fileList" :class="[del ? 'uploadDelectPosition' : '']"
      :action="UploadImg" list-type="picture-card" :on-preview="handlePreview" :before-upload="beforeAvatarUpload"
      :on-remove="handleRemove" :on-success="handleSuccess" :limit="limits" :on-change="handleChange" multiple
      :http-request="selectPicUpload">
      <!-- <el-progress
        v-if="videoFlag"
        class="elProgress"
        type="circle"
        :percentage="videoUploadPercent"
      ></el-progress> -->
      <span v-if="videoFlag">上传中...</span>
      <el-icon v-if="!videoFlag">
        <Plus />
      </el-icon>
    </el-upload>

    <!-- <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog> -->
  </div>
</template>
<!-- <UploadImg :limits="''" del @ImgId="getImageList" /> -->
<!-- limits 上传图片数目限制  :limits="''"表示无限制 默认限制是 2  -->
<!-- del 是否携带删除按钮 默认是不带删除的 -->
<script>
/**上传图片压缩 */
import * as imageConversion from "image-conversion";
/**提示框 */
import { ElMessage } from "element-plus";
/**接口地址 */
import apiUrl from "@/Utils/Config.js";
import CryptoTools from '@/Utils/CryptoTools.js'
export default {
  props: {
    limits: {
      type: Number,
      default: 2,
    },
    del: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      /**图片上传路径 */
      UploadImg: apiUrl.UploadUrl,
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      imgUrls: [],
      /**进度条的进度, */
      videoUploadPercent: 0,
      /**是否显示进度条 */
      videoFlag: false,
    };
  },
  methods: {
    beforeAvatarUpload(rawFile) {
      if (rawFile.type != "image/jpeg" && rawFile.type != "image/png") {
        ElMessage.error("只能上传jpg与png格式");
        return false;
      }
      return new Promise((resolve) => {
        imageConversion.compress(rawFile, 0.4).then((res) => {
          resolve(res);
        });
      });
    },
    handleChange(file, fileList) {
      this.videoFlag = true;
      if (file.status == "success") {
        this.videoFlag = false;
      }
    },
    /**自定义图片上传 */
    selectPicUpload(obj) {
      var _that = this;
      // let fd = new FormData();
      let rawFile = obj.file;
      console.log(rawFile);
      if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
        ElMessage.error("只能上传jpg与png格式");
        return false;
      }
      new Promise((resolve) => {
        imageConversion.compress(rawFile, 0.4).then((res) => {
          resolve(res);
        });
      }).then((res) => {
        // fd.append("file", res, "file.png");
        // _that.$http.UploadImage(fd, (file) => {
        //   _that.videoFlag = false;
        //   _that.videoUploadPercent = 0;
        //   _that.imgUrls.push(file.rows);
        //   _that.$emit("ImgId", _that.imgUrls);
        // });
        CryptoTools.OSSUpload(res, (data => {
          if (data.Success) {
            _that.videoFlag = false;
            _that.videoUploadPercent = 0;
            _that.imgUrls.push(data.rows.url);
            _that.$emit("ImgId", _that.imgUrls);
          } else { }
        }))
      });
    },
    handleSuccess(file, fileList) {
      this.videoFlag = false;
      this.videoUploadPercent = 0;
      this.imgUrls.push(file.url);
      console.log(this.imgUrls);
      this.$emit("ImgId", this.imgUrls);
    },
    handleRemove(file, fileList) {
      let index = this.imgUrls.indexOf(
        file.response?.Data.Item2.Url || file.url
      );
      this.imgUrls.splice(index, 1);
      this.$emit("ImgId", this.imgUrls);
    },
    handlePreview(file) {
      this.previewVisible = true;
      this.previewPath = file.response.data.url;
    },
    /**图片回显 */
    GetImage(val) {
      // console.log(val);
      this.imgUrls = val;
      let arr = [];
      val?.forEach((item, i) => {
        arr.push({ name: i + ".jpg", url: item });
      });
      this.fileList = arr;
      console.log(this.fileList);
    },
    //进度条
    uploadVideoProcess(event, file, fileList) {
    },

    /**粘贴上传实现 */
    // 监听截屏对应事件粘贴方法
    listenerPaste() {
      let _this = this;
      window.addEventListener("paste", function (event) {
        // event.preventDefault();
        event.stopPropagation();
        // 为了截屏时,粘贴在当前的组件,第一次必须促发一次
        (function () {
          document.getElementById("editable").click();
        })();
        _this.paste_img(event);
      });
    },
    // 粘贴方法
    paste_img(e) {
      let _this = this;
      if (e.clipboardData.items) {
        let ele = e.clipboardData.items;
        // 只能为图片的时候才可以粘贴图片
        for (var i = 0; i < ele.length; ++i) {
          if (ele[i].kind == "file" && ele[i].type.indexOf("image/") !== -1) {
            var fileObj = ele[i].getAsFile(); //获取图片信息

            window.URL = window.URL || window.webkitURL;
            var blobUrl = window.URL.createObjectURL(fileObj);
            fileObj.src = blobUrl;
            // console.log(blobUrl);
            this.convertImgToBase64(blobUrl, function (base64Img) {
              let blobData = _this.dataURLtoBlob(base64Img);
              // let formdata = new FormData(); // new一个formdata对象
              let _filename = new Date().getTime() + ".jpg"; // 修改文件名
              // formdata.append("file_upload", blobData, _filename); // key值, 二进制类型文件,文件名
              CryptoTools.OSSUpload(blobData, (data => {
                if (data.Success) {
                  let fileCopy = {
                    ...fileObj,
                    response: JSON.parse(JSON.stringify(data.rows)),
                    percentage: 100,
                    raw: fileObj,
                    status: "success",
                    name: fileObj.name,
                    size: fileObj.size,
                    type: fileObj.type,
                  };
                  _this.fileList.push({
                    name: data.rows.url,
                    url: data.rows.url,
                  });
                  _this.handleSuccess(data.rows, fileCopy, [fileCopy]);
                  window.removeEventListener("paste", _this.paste_img);
                }
              }))

              // _this.$http.UploadImage(formdata, (res) => {
              //   console.log("res", res);
              //   // 格式化文件对象,与el-upload的uploadSuccess方法返回文件对象对应
              //   let fileCopy = {
              //     ...fileObj,
              //     response: JSON.parse(JSON.stringify(res)),
              //     percentage: 100,
              //     raw: fileObj,
              //     status: "success",
              //     name: fileObj.name,
              //     size: fileObj.size,
              //     type: fileObj.type,
              //   };
              //   console.log(res);
              //   _this.fileList.push({
              //     name: res.rows,
              //     url: res.rows,
              //   });
              //   _this.handleSuccess(res, fileCopy, [fileCopy]);
              //   window.removeEventListener("paste", _this.paste_img);
              // });
            });
          }
        }
      } else {
        console.log("non-chrome");
      }
    },
    // base64Img
    convertImgToBase64(url, callback, outputFormat) {
      var canvas = document.createElement("CANVAS"),
        ctx = canvas.getContext("2d"),
        img = new Image();
      img.crossOrigin = "Anonymous";
      img.onload = function () {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL(outputFormat || "image/png");
        // console.log("dataURL", dataURL);
        callback.call(this, dataURL);
        canvas = null;
      };
      img.src = url;
      // console.log(" img.src", img.src);
    },

    //将base64转换为blob
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
  },
  mounted() {
    this.listenerPaste();
  },
};
</script>
<style lang="less" scoped>
// el-upload删除按钮进行定位让其显示出来
.uploadDelectPosition {

  /deep/ .el-upload-list__item-actions {
    // 放大图标进行隐藏
    .el-upload-list__item-preview {
      // display: none;
      position: absolute;
      top: calc(50% - 10px);
      left: calc(50% - 40px);
    }

    .el-upload-list__item-delete {
      position: absolute;
      top: calc(50% - 10px);
      left: calc(-50% - 55px);
    }
  }
}

/deep/ .el-upload {
  position: relative;

  .elProgress {
    svg {
      position: absolute;
      top: calc(50%);
      left: calc(43%);
      transform: translate(-60px, -55px);
      width: 120px !important;
      height: 120px !important;
    }

    span {
      position: relative;
      left: -4px;
      top: 3px;
    }
  }

}
</style>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值