基于element upload封装上传组件

<template>
  <div class="el-upload-wrapper" :id="id">
    <el-scrollbar style="height: 100%">
      <template v-if="!isView">
        <el-upload
          drag
          action="#"
          :http-request="requestFile"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :on-error="handleError"
          :file-list="fileListData"
          :disabled="disabled"
          list-type="picture-card"
          ref="upload"
        >
          <template>
            <img
              class="upload-icon"
              src="@/assets/images/fileicon/download.png"
            />
            {{ uploadName }}上传
          </template>

          <div slot="file" slot-scope="{ file }" class="file-item-wrapper 111">
            <div class="file-item">
              <div class="flex">
                <img class="mr-10" src="@/assets/images/fileicon/file.png" />
                <span class="Fname">{{ file.name }}</span>
              </div>
              <div class="flex">
                <span class="mr-30"
                  >{{ (file.size / 1024 / 1024).toFixed(2) }}Mb</span
                >
                <el-image
                  class="upload-icon"
                  v-if="isImg(file)"
                  :src="imgs"
                  :preview-src-list="[getPreviewImg(file)]"
                >
                </el-image>

                <img
                  class="upload-icon"
                  @click="handleDownload(file)"
                  src="@/assets/images/fileicon/xz.png"
                />
                <img
                  class="upload-icon"
                  @click="handleRemove(file)"
                  src="@/assets/images/fileicon/del1.png"
                />
              </div>
            </div>

            <el-progress
              v-if="file.percentage"
              :percentage="Number(file.percentage.toFixed(2))"
              :status="file.percentage == 100 ? 'success' : ''"
            ></el-progress>
          </div>
        </el-upload>
      </template>

      <template v-else>
        <div
          class="file-item"
          :key="index"
          v-for="(file, index) in fileListData"
        >
          <div class="flex">
            <img class="mr-10" src="@/assets/images/fileicon/file.png" />
            <span class="Fname">{{ file.name }}</span>
          </div>
          <div class="flex">
            <span class="mr-30"
              >{{ (file.size / 1024 / 1024).toFixed(2) }}Mb</span
            >
            <el-image
              class="upload-icon"
              v-if="isImg(file)"
              :src="imgs"
              :preview-src-list="[getPreviewImg(file)]"
            >
            </el-image>

            <img
              class="upload-icon"
              @click="handleDownload(file)"
              src="@/assets/images/fileicon/xz.png"
            />
          </div>
        </div>
      </template>
    </el-scrollbar>
  </div>
</template>

<script>
import { Upload, downloadFile } from "@/api/index.js";
import { newGuid } from "@/utils";
import imgs from "@/assets/images/fileicon/ck.png";

export default {
  props: {
    keyValue: {
      //主键
      type: String,
      default: "",
    },
    isView: {
      type: Boolean,
      default: false, //设备
    },
    uploadName: {
      type: String,
      default: "附件",
    },

    disabled: {
      //禁用
      type: Boolean,
      default: false, //设备
    },
    multiple: {
      type: Boolean,
      default: false, //批量
    },

    filterData: {
      type: Array,
      default: () => [],
    },

    fileList: {
      //文件列表
      type: Array,
      default: () => [],
    },
    fileType: {
      //上传文件类型
      type: Array,
      default: () => ["*"], //gif,jpeg,jpg,png,psd,bmp,rar,zip,pdf,doc,docx,ppt,pptx,txt,xls,xlsx,mp4,wmv
    },
    thumbnailPathAttr: {
      //封面路径字段
      type: String,
      default: "ThumbFilePath",
    },
    filePath: {
      type: String,
      default: "FilePath",
    },
    category: {
      type: String,
      default: "planlibrary",
    },
    memo: {
      type: String,
      default: "",
    },
  },

  data() {
    return {
      id: "upload_" + newGuid(),
      imgSrcList: [],

      imgs,
      srcList: [], // 图片预览
      dialogImageUrl: "",
      dialogTitle: "",
      dialogVisible: false,
      progressFlag: false, //进度条

      statusValue: "",
      filterValue: "",
      filterStatusData: [],
      previewFileData: {},
      fileListHeight: "100px",
      fileListData: [],
    };
  },
  computed: {
    baseUrl() {
      return "";
    },
  },
  watch: {
    fileList: {
      handler(val) {
        this.handleRefresh();
      },
      deep: true,
      immmediate: true,
    },
  },
  mounted() {
    this.fileListHeight = $("#" + this.id).height() - 200 + "px";

    this.handleRefresh();
  },
  methods: {
    handleRefresh() {
      this.$nextTick(() => {
        this.fileListData = this.fileList.map((item) => {
          return {
            name: item.FileName,
            size: item.FileSize,
            url: this.baseUrl + item.FilePath,
            imgurl: this.baseUrl + item.ThumbFilePath,
            response: {
              Data: {
                FilePath: item.FilePath,
                ThumbFilePath: item.ThumbFilePath || item.FilePathThumb,
              },
            },
          };
        });

        //图片预览
        setTimeout(() => {
          this.$previewRefresh();
        }, 200);
      });
    },

    Preview() {},
    downloadFileData() {},

    requestFile(param) {
      //覆盖默认上传方式 自定义上传
      // 获取上传的文件名

      var file = param.file;
      //发送请求的参数格式为FormData
      const formData = new FormData();
      formData.append("formFile", file);
      formData.append("folder", this.category);

      Upload(
        {
          folder: this.category,
        },
        formData
      )
        .then((res) => {
          param.onSuccess(res);
        })
        .catch((err) => {
          param.onError(err);
        });
    },
    beforeAvatarUpload(file) {
      if (this.disabled) {
        return;
      }

      let isFlag = true,
        type = file.name.substring(file.name.lastIndexOf(".") + 1);
      let findIndex = this.fileType.findIndex((node) => node == type);
      let notAllow = ["exe", "EXE", "dll"];

      if (
        (findIndex == -1 && this.fileType.indexOf("*") == -1) ||
        notAllow.indexOf("*") > -1
      ) {
        isFlag = false;
        this.$nextTick(() => {
          this.$message({
            type: "warning",
            message: "此类型文件不允许上传!",
          });
        });
      }
      return isFlag;
    },
    // handleAvatarProgress(event, file, fileList) {
    //   //文件上传时
    //   this.uploadPercent = Number(file.percentage.toFixed(2));
    // },
    handleAvatarSuccess(res, file) {
      //回调

      this.$emit("success", res.Data, file);

      //图片预览
      setTimeout(() => {
        this.$previewRefresh();
      }, 200);
    },
    handleRemove(file) {
      // 实现缩略图模板时删除文件
      let fileList = this.$refs.upload.uploadFiles;
      let index = fileList.findIndex((fileItem) => {
        return fileItem.uid === file.uid;
      });
      fileList.splice(index, 1);
      this.$emit("success", fileList);
    },
    handleOpenView(event, file) {
      let imgDom = $(event.target)
        .parents(".file-item-wrapper")
        .find(".el-image img");

      imgDom.trigger("click");
    },
    handlePictureCardPreview(file) {
      let response = file.response;
      if (response) {
        this.previewFileData = response.data[0];
      } else {
        this.previewFileData = file;
      }

      this.$nextTick(() => {
        this.$refs.fileview.open();
      });
    },
    handleDownload(file) {
      downloadFile({ fileName: file.response.Data.FilePath }).then((res) => {
        if (!res) {
          return;
        }
        //将blob对象转换为域名结合式的url
        let blobUrl = window.URL.createObjectURL(res.data);
        let link = document.createElement("a");
        document.body.appendChild(link);
        link.style.display = "none";
        link.href = blobUrl;
        // 设置a标签的下载属性,设置文件名及格式,后缀名最好让后端在数据格式中返回
        link.download = file.name;
        // 自触发click事件
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(blobUrl);
      });
    },
    handleError(err, file, fileList) {
      this.$message({
        type: "warning",
        message: "此类型文件不允许上传!",
      });
    },
    isImg(file) {
      if (!file.name) {
        return -1;
      }
      let type = file.name.split(".")[1].toLowerCase();
      //判断是否是图片
      return (
        ["gif", "jpeg", "jpg", "png", "bmp"].findIndex((node) => node == type) >
        -1
      );
    },
    isVideo(file) {
      if (!file.name) {
        return -1;
      }
      let type = file.name.split(".")[1].toLowerCase();
      //判断是否是图片
      return (
        ["wmv", "avi", "dat", "asf", "mpeg", "mpg", "mp4"].findIndex(
          (node) => node == type
        ) > -1
      );
    },
    isMp3(file) {
      if (!file.name) {
        return -1;
      }
      let type = file.name.split(".")[1].toLowerCase();
      //判断是否是图片
      return ["mp3"].findIndex((node) => node == type) > -1;
    },
    isPdf(file) {
      if (!file.name) {
        return -1;
      }
      let type = file.name.split(".")[1].toLowerCase();
      //判断是否是图片
      return ["pdf"].findIndex((node) => node == type) > -1;
    },
    getPreviewImg(file) {
      //文件封面
      if (this.isImg(file)) {
        // console.log(file);
        if (file.response) {
          let response = file.response;
          if (response.Data) {
            // let path = response.Data[this.thumbnailPathAttr];
            let path = response.Data[this.filePath];
            // console.log(`api/api/File/DownloadByPath?fileName=${path}`)
            // return "/api" + path;
            return `api/api/File/DownloadByPath?fileName=${path}`;
          }
        }
      } else {
        let type = file.name.split(".")[1].toLowerCase();
        try {
          return require(`@/assets/images/filetype/${type}.png`);
        } catch (e) {
          return require(`@/assets/images/filetype/file.png`);
        }
      }

      return "";
    },
    getFileList() {
      let list = [];
      this.$refs.upload.uploadFiles.forEach((item) => {
        let response = item.response;
        if (!!response) {
          const { Data } = response;
          let path = Data.FilePath;

          list.push({
            FolderId: this.keyValue,
            FileName: item.name,
            Memo: this.memo,
            Category: this.category,
            FilePath: path,
            FileSize: item.size,
            FileExtensions: "." + Data.FilePath.split(".")[1],
            FileType: Data.FilePath.split(".")[1],
            FilePathThumb: Data.ThumbFilePath,
          });
        }
      });
      return list;
    },

    clearFiles() {
      this.$refs.upload.clearFiles();
    },
  },
};
</script>
<style lang="scss" scoped>
.el-upload-wrapper {
  .upload-icon {
    margin-right: 5px;
  }

  ::v-deep.el-upload--picture-card,
  ::v-deep.el-upload-list__item {
    height: 135px;
    width: 135px;
  }

  ::v-deep.el-upload {
    .el-upload-dragger {
      width: 100%;
      height: 100%;
      border: none;
      background-color: transparent;

      .el-icon-plus {
        font-size: 30px;
        margin: 13px 0 16px;
      }
    }

    .el-upload-list {
      display: none;
    }
  }

  ::v-deep .el-scrollbar__view {
    height: 100%;

    > div {
      height: 100%;
    }
  }

  ::v-deep .el-upload--picture-card {
    width: 100%;
    height: 100%;
    line-height: normal;
    border: none;
  }

  ::v-deep .el-upload-dragger {
    width: 100%;
    height: 46px;
    border-radius: 4px;
    background: #0873ee0d;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .file-item-wrapper {
    height: 100%;
  }

  ::v-deep .el-upload-list--picture-card .el-upload-list__item {
    height: 46px;
    width: 100%;
    margin-right: 0;
    border: none;
    border-radius: 4px;
  }

  .file-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    line-height: 46px;
    background: #0873ee0d;
    padding: 0 20px;
    margin-bottom: 10px;
    color: #666666ff;

    .flex {
      display: flex;
      align-items: center;
    }

    ::v-deep .el-image {
      display: flex;
      align-items: center;
    }

    .upload-icon {
      cursor: pointer;
      margin-right: 10px;

      &:hover {
        opacity: 0.7;
      }
    }

    .Fname {
      color: #00000099;
    }

    .mr-10 {
      margin-right: 10px;
    }

    .mr-20 {
      margin-right: 20px;
    }

    .mr-30 {
      margin-right: 30px;
    }
  }
}
</style>

-----------------------------------------------------------------------------------------------
2:引入组件
import UploadBox from "@/components/Upload";

3:使用组件
 <el-form-item label="" prop="FileList">
            <upload-box
              :disabled="disabled"
              :isView="type === 'view'"
              ref="uploadbox"
              @success="handleChangeFile"
              :category="'AppointmentRecord'"
              :fileList="formData.FileList"
            ></upload-box>
 </el-form-item>

![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/9d5d7ce86e284edca2cb98a85cb1fba3.png#pic_center)

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个使用 Element UI 二次封装Upload 上传组件的示例代码: ``` <template> <div> <el-upload :action="uploadUrl" :headers="headers" :data="formData" :multiple="multiple" :show-file-list="showFileList" :limit="limit" :on-exceed="onExceed" :before-upload="beforeUpload" :on-success="onSuccess" :on-error="onError" :on-progress="onProgress" > <el-button type="primary" :disabled="uploading">{{ buttonText }}</el-button> <div slot="tip" class="el-upload__tip">{{ tip }}</div> </el-upload> </div> </template> <script> export default { name: "MyUpload", props: { uploadUrl: { type: String, default: "" }, headers: { type: Object, default: () => ({}) }, formData: { type: Object, default: () => ({}) }, multiple: { type: Boolean, default: false }, showFileList: { type: Boolean, default: true }, limit: { type: Number, default: 0 }, buttonText: { type: String, default: "上传文件" }, tip: { type: String, default: "只能上传jpg/png文件,且不超过500kb" } }, data() { return { uploading: false }; }, methods: { onExceed(files, fileList) { this.$message.warning(`只能上传${this.limit}个文件`); }, beforeUpload(file) { const isJPG = file.type === "image/jpeg" || file.type === "image/png"; const isLt500K = file.size / 1024 < 500; if (!isJPG) { this.$message.error("上传图片只能是 JPG/PNG 格式!"); return false; } if (!isLt500K) { this.$message.error("上传图片大小不能超过 500KB!"); return false; } return true; }, onSuccess(response, file, fileList) { this.uploading = false; this.$emit("upload-success", response, file, fileList); }, onError(err, file, fileList) { this.uploading = false; this.$emit("upload-error", err, file, fileList); }, onProgress(event, file, fileList) { this.uploading = true; this.$emit("upload-progress", event, file, fileList); } } }; </script> <style> /* 可以根据自己的需要修改样式 */ .el-upload__tip { font-size: 14px; color: #999; margin-top: 10px; } </style> ``` 这个 Upload 组件支持以下 props: - `uploadUrl`:上传文件的接口地址 - `headers`:上传请求的 headers - `formData`:上传请求的 formData - `multiple`:是否支持多选文件 - `showFileList`:是否显示已上传文件列表 - `limit`:最多上传文件个数 - `buttonText`:上传按钮的文本 - `tip`:上传提示信息 这个 Upload 组件还支持以下事件: - `upload-success`:上传成功的回调函数,参数为 response、file 和 fileList - `upload-error`:上传失败的回调函数,参数为 err、file 和 fileList - `upload-progress`:上传进度的回调函数,参数为 event、file 和 fileList 使用示例: ``` <template> <div> <my-upload :upload-url="uploadUrl" :headers="headers" :form-data="formData" :multiple="multiple" :show-file-list="showFileList" :limit="limit" :button-text="buttonText" :tip="tip" @upload-success="onUploadSuccess" @upload-error="onUploadError" @upload-progress="onUploadProgress" ></my-upload> </div> </template> <script> import MyUpload from "@/components/MyUpload"; export default { components: { MyUpload }, data() { return { uploadUrl: "https://xxx.com/upload", headers: { token: "xxx" }, formData: { type: "avatar" }, multiple: false, showFileList: true, limit: 1, buttonText: "上传头像", tip: "只能上传jpg/png文件,且不超过500kb" }; }, methods: { onUploadSuccess(response, file, fileList) { console.log("上传成功", response, file, fileList); }, onUploadError(err, file, fileList) { console.log("上传失败", err, file, fileList); }, onUploadProgress(event, file, fileList) { console.log("上传进度", event, file, fileList); } } }; </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值