elementUI实现上传excel文件并传给后端

发布于:2024-06-22 ⋅ 阅读:(137) ⋅ 点赞:(0)

我们选择一个按钮来实现上传,点击上传按钮,可从本地选择文件上传,确定后传递给后端。

首先,封装一个按钮:

                    <el-upload
                        style="display: inline-block"
                        action="string"
                        :limit="1"
                        :file-list="fileList"
                        :on-error="loadFileError"
                        :on-success="loadFileSuccess"
                        :before-upload="beforeUpload"
                        accept=".xlsx,.xls"
                        :show-file-list="false"
                        :http-request="uploadFile"
                    ><el-button type="primary" plain>导入关联商品</el-button></el-upload>

我们来看一下这里面的每个属性的作用:

limit: 代表一次可上传的文件数量
file-list: 代表自己定义的属性
on-error: 代表导入文件失败的时候提示的方法
on-success:代表导入文件成功提示的方法
before-upload:代表在上传前检查文件的格式、数据大小、信息等,判定文件是否能够上传
show-file-list:代表是否显示文件列表,false不显示
http-request:本次用来进行上传给后端的方法

接下来是script部分:

定义属性:

export default {
  name: "conferenceSignCard",
  data() {
    return {
      fileList: [], // 导入的文件
    };
  },
}

导入文件失败的提示方法:

    // 导入失败,其中$message为elementui的消息提醒组件
    loadFileError() {
      this.$message({
        message: "文件上传失败!",
        type: "error",
      });
    },

导入文件成功的提示方法:

    loadFileSuccess() {
      this.$message({
        message: "文件上传成功!",
        type: "success",
      });
    },

格式校验:上传前检查文件格式、数据大小等信息,判断是否能够上传。这里可导入xlsx和xls文件格式。

    // 导入前检查文件
    beforeUpload(file) {
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!extension && !extension2) {
        this.$message({
          message: "上传模板只能是 xls、xlsx格式!",
          type: "error",
        });
      }
      if (!isLt2M) {
        console.log("上传模板大小不能超过 2MB!");
        this.$message({
          message: "上传模板大小不能超过 2MB!",
          type: "error",
        });
      }
      return extension || extension2 || isLt2M;
    },

传递给后端的方法:

    uploadFile(param){
      const File = param.file;
      let formDataInfo = new FormData();
      formDataInfo.append("file", File);
      loadConferenceFile(formDataInfo).then((res) => {
          this.$message({
            message: res.data,
            type: "success",
          });
      });
    },
loadConferenceFile(formDataInfo){
    return axios.post("/signCard/loadConferenceFile",formDataInfo)
  }

完成!

参考文章:

elementUI加springboot实现上传excel文件给后端并读取excel_前端上传excel文件给后端可以吗-CSDN博客


网站公告

今日签到

点亮在社区的每一天
去签到