Element-ui的附件上传下载组件封装以及预览等功能

1,459 阅读1分钟

父组件代码

 <file-list
      :readonly="disable"
      :fileListData="fileListDataResoluExplain"
      @downloadCurrentFile="downloadFileExplain"
      @deleteCurrentFile="deleteFileExplain"
      @uploadSuccess="uploadSuccessExplain"
      @downAllFiles='downFileMaterials'>
      </file-list>

引入子组件封装的代码

<template>
  <!-- 上传附件 -->
  <div class="fileComponent">
    <div class="fileList" style="width: 80%; float: left">
      <ul>
        <li v-for="(item, index) in fileListData.fileInfoList" :key="index">
          <input
            class="sort"
            type="text"
            v-model="item[fileListData.sortKey]"
            v-if="fileListData.sortStatus === true"
          />
          <span class="fileName" @click="preFile(item)">{{
            item[fileListData.fileName]
          }}</span>
          <div class="fileHandle">
            <span @click="downloadCurrentFile(item)" class="download"
              >下载</span
            >
            <span @click="deleteCurrentFile(item, index)" class="deleteFile"
              >删除</span
            >
          </div>
        </li>
      </ul>
    </div>
    <div class="fileListHandle">
      <el-upload
        class="uploadFile"
        ref="upload"
        :auto-upload="true"
        :headers="getheaders"
        :action="fileListData.urlApi"
        :multiple="false"
        :data="fileListData.fileListMsg"
        :before-upload="beforeAvatarUpload"
        :show-file-list="false"
        name="file"
        :on-success="uploadSuccess"
        :on-error="onError"
      >
        <el-button size="small">上传附件</el-button>
      </el-upload>
      <el-button
        size="small"
        @click="updateSort"
        v-if="fileListData.sortStatus === true"
      >
        重新排序
      </el-button>
      <el-button @click="downAllFiles" v-if="downloadFileBut"
        >下载全部</el-button
      >
    </div>
  </div>
</template>

<script>
/**
 * 父组件传入的附件的相关配置
 * fileListDataResolu:{
 *      urlApi:'',  //上传附件接口
 *      sortApi:'', //重新排序接口
 *      downFlieAll:'', //下载全部附件接口,待测试
 *      fileListMsg:{}, //额外携带参数
 *      fileInfoList:[], //附件list数据
 *      sortKey:'sort', //排序码KEY
 *      fileName:'fileName', //附件名称KEY
 *      sortStatus:Boolean, //是否显示排序码和排序按钮
 *      needPreview: Boolean,//是否需要单独的预览功能
 *  }
 *  上传成功后、下载、删除需要需要单独调用父组件的方法(父组件单独处理各自的业务)
 */
import cookie from "@/assets/util/cookie";
import { APIAuthorization } from "@/assets/config";
import { API } from "../api/messagePublish";

export default {
  name: "fileList",
  props: {
    fileListData: Object, //附件的一些配置信息
    downloadFileBut: {
      default: true,
      type: Boolean,
    },
  },
  computed: {
    getheaders() {
      let headers = {};
      headers["Authorization"] = APIAuthorization;
      headers["Sinosoft-Auth"] = cookie.get("Sinosoft-Auth", {
        path: "/",
      });
      return headers;
    },
  },
  data() {
    return {
      formInfo: [],
    };
  },
  inject: ["previewFile"],
  methods: {
    /**
     * 预览文件
     */
    preFile(item) {
      if (this.fileListData.needPreview) {
        this.$emit("previewFileMethod", item);
        return;
      }
      this.previewFile(
        {
          ...item,
          url: API.file.getNoFlowDownLoadById,
          previewParams: {
            id: item.id,
          },
        },
        item.fileExts
      );
    },
    //上传之前的回调
    beforeAvatarUpload(file) {
      let numSize =
        this.fileListData.fileInfoList.length &&
        this.fileListData.fileInfoList.reduce((pre, cur) => {
          return (pre += cur.fileSize);
        }, 0);

      const isLt2M = file.size / 1024 / 1024 < (this.fileListData.size || 5);
      const isLt20M =
        (numSize - 0 + file.size) / 1024 / 1024 <
        (this.fileListData.totalSize || 20);
      if (!isLt2M) {
        this.$message.error(
          `上传文件大小不能超过 ${this.fileListData.size || 5}MB!`
        );
        return false;
      }
      if (!isLt20M) {
        this.$message.error(
          `上传文件总大小不能超过 ${this.fileListData.totalSize || 20}MB!`
        );
        return false;
      }
      return true;
    },
    downloadCurrentFile(item) {
      this.$emit("downloadCurrentFile", item);
    },
    /*删除、下载当前附件需要调用父组件的方法,根据接口不同单独处理业务*/
    deleteCurrentFile(flieParams, eq) {
      let fileData = flieParams;
      fileData.index = eq;
      //splice(i, 1);
      this.$emit("deleteCurrentFile", fileData);
    },
    uploadSuccess(res) {
      //let defaultSort = '';
      res.data[this.fileListData.sortKey] =
        this.fileListData.fileInfoList.length + 1;
      this.$emit("uploadSuccess", res.data);
    },
    /*下载全部,待测试*/
    downAllFiles() {
      this.$emit("downAllFiles");
    },
    onError(res) {
      console.log(res);
    },
    /*附件排序*/
    updateSort() {
      let length = this.fileListData.fileInfoList.length;
      if (length > 0) {
        /*this.fileListData.fileInfoList.sort((a,b)=>{
                        return a[this.fileListData.sortKey] - b[this.fileListData.sortKey]
                    });*/
        let sortMsg = this.fileListData.fileInfoList.sort((a, b) => {
          return a[this.fileListData.sortKey] - b[this.fileListData.sortKey];
        });
        if (this.fileListData.sortApi === "") {
          this.fileListData.fileInfoList = sortMsg;
        } else {
          this.$http
            .post(this.fileListData.sortApi, sortMsg)
            .then((res) => {
              this.$message.success(res.msg);
            })
            .catch((error) => {
              console.log(error);
              this.$message.warning("操作失败!");
            });
        }
      } else {
        this.$message.warning("没有可排序的附件");
      }
    },
  },
};
</script>

<style scoped lang="less">
</style>