3

Spring Boot 2.x基础教程:多个文件的上传

 3 years ago
source link: http://blog.didispace.com/spring-boot-learning-21-4-4/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

昨天,我们介绍了如何在 Spring Boot中实现文件的上传 。有读者问:那么如果有多个文件要同时上传呢?这就马上奉上,当碰到多个文件要同时上传的处理方法。

动手试试

本文的动手环节将基于 Spring Boot中实现文件的上传 一文的例子之上,所以读者可以拿上一篇的例子作为基础来进行改造,以体会这之间的区别,下面也主要讲解核心区别的地方。

第一步:修改文件上传页面的上传表单

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>文件上传页面 - didispace.com</title>
</head>
<body>
<h1>文件上传页面</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
    文件1:<input type="file" name="files"><br>
    文件2:<input type="file" name="files"><br>
    <hr>
    <input type="submit" value="提交">
</form>
</body>
</html>

可以看到这里多增加一个input文件输入框,同时文件输入框的名称修改为了files,因为是多个文件,所以用了复数。注意:这几个输入框的name是一样的,这样才能在后端处理文件的时候组织到一个数组中。

第二步:修改后端处理接口

@PostMapping("/upload")
@ResponseBody
public String create(@RequestPart MultipartFile[] files) throws IOException {
    StringBuffer message = new StringBuffer();

    for (MultipartFile file : files) {
        String fileName = file.getOriginalFilename();
        String filePath = path + fileName;

        File dest = new File(filePath);
        Files.copy(file.getInputStream(), dest.toPath());
        message.append("Upload file success : " + dest.getAbsolutePath()).append("<br>");
    }
    return message.toString();
}

几个重要改动:

MultipartFile
MultipartFile

更多本系列免费教程连载「点击进入汇总目录」

测试验证

第一步:启动Spring Boot应用,访问 http://localhost:8080 ,可以看到如下的文件上传页面。

FRV3qqq.png!mobile

第二步:选择2个不大于2MB的文件,点击“提交”按钮,完成上传。

如果上传成功,将显示类似下面的页面:

miUb2if.png!mobile

你可以根据打印的文件路径去查看文件是否真的上传了。

代码示例

本文的相关例子可以查看下面仓库中的 chapter4-4 目录:

如果您觉得本文不错,欢迎 Star 支持,您的关注是我坚持的动力!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK