Upload files in batches, upload files with input, and the backend receives them as List<MultipartFile>type

Upload files in batches, upload files with input, and the backend receives them as List type

Recently, the company asked for a function to upload files in batches. In the past, importing Excel tables and uploading pictures were all done by uploading one file. This time, it really made me difficult during the development process, especially when connecting the front and back ends. Make a note here.

1. Backend interface

The backend interface is like this. Compared with single file upload, the MultipartFile type data is turned into a collection. This MultipartFile is still uploaded in FormData, and the "yqId" and "depId" here are also in FormData.

//批量上传文件
@PostMapping("/batchUploadContract")
public Result batchUploadContract(@RequestParam("yqId") String yqId, 
                                  @RequestParam("depId") String depId, 
                                  @RequestParam("fileList") List<MultipartFile> fileList) {
    
    
    Result result = null;
    try {
    
    
        SysUserHetongDto params = new SysUserHetongDto();
        params.setYqId(yqId);
        params.setDepId(depId);
        result = Result.OK("上传成功!", userHetongService.batchUploadContract(params, fileList));
    } catch (Exception e) {
    
    
        e.printStackTrace();

        result = Result.error("上传失败!" + e.getMessage());
    } finally {
    
    
        return result;
    }
}

2. Front-end docking

The front-end framework is "Ant Design". I also considered using its upload component at the beginning. It may be because I am not familiar with the component. During the docking process, I always encountered various problems, or it would be called multiple times. interface (select several files and adjust them several times), or the data passed is not of binary type and cannot be received by the backend. After struggling for a long time, the connection was not successful.

Finally decided to use input in vue for multi-file upload

In the "template" tag

<template>
	<div>
      <input type="file" @change="uploadFile" multiple="multiple">
    </div>
</template>

In the "script" tag

<script>
import axios from 'axios'
export default {
      
       
	methods: {
      
      
	    uploadFile(event) {
      
        //事件名称可以自己取,我这里是event
	      // console.log("uploadFile event", event)
	      console.log("uploadFile files", event.target.files)
	      // console.log("uploadFile typeof", typeof event.target.files[0])
	      let files = event.target.files;  //input上传的文件一般是在target.files下,是一个File类型的集合
	      const headers = {
      
      
	        'X-Access-Token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2OTQ0MTgyNjEsInVzZXJuYW1lIjoi5Y2h5LiA6L2mIn0.J0l4AbdlnZKszqk8QDRCGbLrR6vfNynkz1K2mWJgX4s',  //请求token,我这里的名称是X-Access-Token
	        'Content-Type': 'multipart/form-data',  // 文件上传类型
	      };
	      let url = 'http://127.0.0.1:8080/jeecg-boot/hetong/batchUploadContract';
	      let form = new FormData();  //FormData中的参数
	      form.append('depId', '74f801bcffe745c3a20caad20985db9f');
	      form.append('yqId', 'ca6d914f8b0840928f787f4073ccc023');
	
	      //上传集合类型的文件,后端以List<MultipartFile>接收
	      for(let i = 0; i < files.length; i++) {
      
      
	        form.append('fileList', files[i]);
	      }
	
	      //调用后端接口
	      axios.post(url, form, {
      
      headers:headers}).then((res) => {
      
      
	        //console.log("uploadFile res", res)
	        // if(res.data.code == 200) {
      
      
	        //   console.log(res.data.message)
	        // }
	      })
	      return false;
	    }
	  },
  	},
}
</script>

3. Test

After selecting the file to upload, view the front-end console

Insert image description here

These two files are selected for uploading and are of File type, but what we want is binary type.

In the upload file method, it is added to the FormData in a loop and it becomes a binary type.

Insert image description here

Looking at Network, you can see that File type files have been converted to binary types.

Insert image description here

It will happen that depending on how many files are selected, there will be as many file parameters with the same name (in my case, it is fileList). However, this does not affect it. After selecting several files, the backend will receive several files.

Backend debugging

Insert image description here

You can see that the two files have been transferred in, and it was finally successful.

Guess you like

Origin blog.csdn.net/studio_1/article/details/132812520