current position:Home>Vue excel file upload

Vue excel file upload

2022-04-29 08:30:27Small marinated egg

Use element Components el-upload

  <el-upload
         ref="upload"action="doUpload"
         :limit="1"
         :file-list="fileList"
         :before-upload="beforeUpload">
<el-button type="primary" style="width: 150px" @click="uploadFile"> Upload files </el-button>
        <div slot="tip" class="el-upload__tip"></div>
  </el-upload>

File to judge


      beforeUpload(file){
        console.log(file,' file ');
        this.files = file;
        const extension = file.name.split('.')[1] === 'xls'
        const extension2 = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 20
        if (!extension && !extension2) {
          this.$message.warning(' Upload template can only be  xls、xlsx Format !')
          return
        }
        if (!isLt2M) {
          this.$message.warning(' Upload template size cannot exceed  20MB!')
          return
        }
        this.fileName = file.name;
        return false //  return false It won't upload automatically 
      },

Upload to backend

 submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {

            console.log(' Upload '+this.files.name)
            if(this.fileName == ""){
              this.$message.warning(' Please select the file to upload !')
              return false
            }
            let fileFormData = new FormData();
            fileFormData.append('file', this.files, this.fileName);//filename It's a key ,file Is the value , Is the file to be transmitted ,test.zip Is the file name to be transferred 
            let requestConfig = {
              headers: {
                'Content-Type': 'multipart/form-data'
              },
            }


            impExcel(fileFormData, requestConfig).then((res) => {
              console.log(" Upload excel file ")
            })
            // Close the pop-up window 
            this.dialogVisible = false;
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

introduce js Fonda

export function impExcel(data) {
  return request({
    url: '/api/upExcel',
    method: 'post',
    data: data
  })
}

Back end

 @PostMapping(value = "/upExcel")
    public void readExcel(@RequestParam(value="file", required = false)  MultipartFile file){
        long t1 = System.currentTimeMillis();
        List<ArcBasicExcel> list = ExcelUtils.readExcel("", ArcBasicExcel.class, file);
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("read over! cost:%sms", (t2 - t1)));
    }

effect

Welcome to my official account. :

                

 

copyright notice
author[Small marinated egg],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290609010302.html