pc文件上传

1.代码:

<template>
  <div>
    <el-upload
      :multiple="true"
      :auto-upload="true"
      :headers="headers"
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"
      :on-success="handleUploadSuccess"
      :on-remove="handleRemove"
      :file-list="fileList">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传"doc", "xls", "ppt", "txt", "pdf"文件,且不超过5MB</div>
    </el-upload>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
export default {
  props:{
    fileList1:{ // 文件列表回显
      type:Array,
      default:[]
    }
  },
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      fileList: this.fileList1, // 文件列表
      fileType:["doc", "xls", "ppt", "txt", "pdf"], // 文件类型
      fileSize:5, // 文件大小
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      submitFileUrl:this.fileList1 // 服务器返回的地址
    }
  },
  methods: {
    // 删除
    handleRemove(file){
      for (let i = 0; i < this.submitFileUrl.length; i++) {
        if(this.submitFileUrl[i].name == file.name ){
          this.submitFileUrl.splice(this.submitFileUrl.indexOf(this.submitFileUrl[i].name), 1)
        }
      }
      this.$emit("input",this.submitFileUrl)
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.fileList = this.fileList.slice(0,-1);
          this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.fileList = this.fileList.slice(0,-1);
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.submitFileUrl.push({name:res.data.fileName,url:res.data.url})
      this.$message.success("上传成功");
      this.$emit("input",this.submitFileUrl)
    },
  }
}
</script>

<style scoped>

</style>

2.界面:

猜你喜欢

转载自blog.csdn.net/weixin_46029283/article/details/132037015
PC: