Spring MVC如何上传文件

代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

@Slf4j
@RestController
public class FileUploadController {

    @PostMapping("/upload")
    private ResponseVo upload(
            @RequestPart("file") MultipartFile file,
            @RequestPart("files") MultipartFile[] files) throws IOException {

        log.info("上传的信息: file={}, files={}", file.getSize(), files.length);

        if (!file.isEmpty()) {
            file.transferTo(Paths.get(
                    "C:\\Users\\wujj\\Desktop\\Tmp5\\",
                    file.getOriginalFilename()));
        }

        if (files.length > 0) {
            for (MultipartFile multipartFile : files) {
                if (!multipartFile.isEmpty()) {
                    multipartFile.transferTo(Paths.get(
                            "C:\\Users\\wujj\\Desktop\\Tmp5\\",
                            multipartFile.getOriginalFilename()));
                }
            }
        }

        return new ResponseVo("00000", "成功");
    }
}

Postman上传时配置如下:

2021-08-02-11-18-24

MultipartFile应用

说起来有点糟心,Spring MVC的MultipartFile非常的好用,但是我们代码使用这个工具的方式真的不是很优雅:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18

    public ResponseVo<Object> importCompany(
            @RequestAttribute(value = APICons.REQUEST_USER, required = false) JSONObject user,
            MultipartHttpServletRequest request) throws IOException {
        
        Map<String, MultipartFile> fileMap = request.getFileMap();
        List<String> msgList = new ArrayList<>();
        for (Map.Entry<String, MultipartFile> stringMultipartFileEntry : fileMap.entrySet()) {
            Sheet sheet = new Sheet(1, 1, CompanyRequestMode.class);
            EasyExcelFactory.readBySax(
                    stringMultipartFileEntry.getValue().getInputStream(), 
                    sheet,
                    new ExcelCompanylistener(this.companyService, this.packageService, user.getString("id"), user.getString("name"), msgList));
        }
        
        return ResponseVo.ok(msgList);
    }

我们没有在参数中接受MultipartFile类型的参数,而是从request中获取了一个Map类型的,感觉这样编码并不是很优雅。