满心记 我在人间混日子

ElementUI多附件上传

最近在做表单提交,需要选取多附件进行上传,蛮简单的一个功能,由于拿来主义惯了,所以第一想法找现成的,后来在网上也看了一些例子,大多都有点问题,或者不适用,后来自己鼓捣了一个,这里也记录一下

我这里会分享前端 + 后台封装以及传参、最终存储到文件服务器的全过程,有兴趣的可以往下看

我这里用到的架子是:Pigx的微服务商用版架构

整体架构采用:

  1. 前端:VUE + ElementUI
  2. 后端:JAVA
  3. 文件服务:Minio
  4. 数据库:Mysql

应用安装部分可参考:服务器环境初始化麻烦?看这一篇全搞定

上传组件

前端代码

<el-upload
  :headers="headers"
  action="#"
  :file-list="fileList"
  :on-exceed="handleExceed"
  :auto-upload="false"
  :on-change="changeFile"
  :limit="10"
  :on-remove="handleRemove"
>
  <el-button size="small" type="primary">点击上传</el-button>
</el-upload>
import store from "@/store";
import {
  uploadFile,
  getByReportId,
  delObj,
} from "@/api/module/mxFile";

export default {
  data() {
    return {
      headers: {
        Authorization: "Bearer " + store.getters.access_token,
      },
      visible: false,
      canSubmit: false,
      fileList: [],
      fileListTmp: [],
    };
  },
  methods: {
    init(id) {
      this.fileList = [];
      this.fileListTmp = [];
      this.dataForm.createUser = this.userInfo.name;
      this.dataForm.reportId = id;
      this.visible = true;
      this.canSubmit = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.reportId) {
          getObj(this.dataForm.reportId).then((response) => {
            this.dataForm = response.data.data;
          });
          this.initFiles();
        }
      });
    },
    /**
     * 初始化附件
     */
    initFiles() {
      getByReportId(this.dataForm.reportId).then((response) => {
        let _data = response.data.data;
        if (_data !== null) {
          _data.forEach((item) => {
            let obj = new Object();
            obj.url = item.fileUrl;
            obj.name = item.originalName;
            obj.fileId = item.fileId;
            this.fileList.push(obj);
          });
        }
      });
    },
    /**
     * 文件上传触发
     */
    changeFile(fileList) {
      this.fileListTmp.push(fileList);
    },
    handleExceed() {
      this.$message.warning(`当前限制上传10个附件!`);
    },
    /**
     * 删除附件
     */
    handleRemove(file) {
      delObj(file.fileId).then((res) => {
        this.$notify.success("删除成功");
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.canSubmit = false;
          if (this.dataForm.reportId) {
            putObj(this.dataForm)
              .then((data) => {
                this.$notify.success("修改成功");

                this.upload(this.dataForm.reportId);
                this.visible = false;
                this.$emit("refreshDataList");
              })
              .catch(() => {
                this.canSubmit = true;
              });
          } else {
            addObj(this.dataForm)
              .then((response) => {
                this.$notify.success("添加成功");
                this.upload(response.data.data);
                this.visible = false;
                this.$emit("refreshDataList");
              })
              .catch(() => {
                console.log("error");
                this.canSubmit = true;
              });
          }
        }
      });
    },
    upload(reportId) {
      this.fileListTmp.forEach((item) => {
        let formDate = new FormData();
        formDate.append("file", item.raw);
        formDate.append("reportId", reportId);
        uploadFile(formDate);
      });
    },
  },
};
export function uploadFile(obj) {
    return request({
        url: '/module/mxFile/uploadFile',
        method: 'post',
        data: obj
    })
}

从上述代码可以看到,我是在上传和修改的时候触发上传附件操作,比较粗糙,仅供参考

后端代码

/**
* 附件上传
*/
@PostMapping("/uploadFile")
@ApiOperation(value = "附件上传", notes = "附件上传")
public R uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("reportId") String reportId) {
    return mxFileService.uploadFile(file, reportId);
}

发表评论

提交评论