7.10 文件上传

第 57 节 / 共 81 节 课程:前后端穿透

下面是用Spring Boot实现文件上传的例子,这是一个完整的eclipse项目,点击下载后导入,可直接运行。

文件上传后会保存在../../../upload-dir文件夹,启动前会清空这个文件夹内所有文件:

示意图

这个例子用到了网页模板,在file../../../uploadController.java里,listUploadfiles函数响应/file请求,返回../../../uploadForm:

@GetMapping("/file")

public String listUploadedFiles(Model model)throws IOException{

model.addAttribute("files",storageService

.loadAll()

.map(path->MvcUriComponentsBuilder

.fromMethodName(FileUploadController

.class,

"serveFile",path

.getFileName()

.toString()).build().toUri().toString()).collect(Collectors.toList()));

    return "../../../uploadForm";
}

而实际上,这个../../../uploadForm是一个html模板,它位于src/main/rescources/templates文件夹里,upLoadForm.html:

<htmlxmlns:th="https://www.thymeleaf.org">
<body>
<divth:if="${message}">
    <h2th:text="${message}"/>
</div>
<div>
    <formmethod="POST"enctype="multipart/form-data"action="/file">
    <table>
    <tr>
        <td>Fileto../../../upload:</td>
        <td><inputtype="file"name="file"/>
        </td>
    </tr>
    <tr>
        <td></td>
        <td><inputtype="submit"value="Upload"/>
        </td>
    </tr>
    </table>
    </form>
</div>
<div>
    <ul>
        <lith:each="file : ${files}"><ath:href="${file}"th:text="${file}"/>
        </li>
    </ul>
</div>
</body>
</html>

它是一个称为thymeleaf的框架,类似于前端的Vue,但是它是后端直接填数据的,为了使用它,需要在pom.xml的dependencies中添加这一行(项目里的已经添加):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

../../uploadForm.html里面的${message}和${file}就是属性,需要在java后台里设值,如果没有值,那么不会显示。上传成功后,会设值message属性的值:

@PostMapping("/file")

public String handleFileUpload(@RequestParam("file")MultipartFile file,RedirectAttributes redirectAttributes){

storageService.store(file);

redirectAttributes.addFlashAttribute("message","You successfully

../../uploaded "+file.getOriginalFilename()+"!");

    return "redirect:/file";
}

message设置成了“You successfully ../../uploaded ”加上文件名,于是页面变成了这样:

示意图

最后,配置文件application.properties(位于src/main/rescources/)里限定了上传文件的最大值:

spring.servlet.multipart.max-file-size=128KB

spring.servlet.multipart.max-request-size=128KB

《前后端穿透》课程目录

按教材顺序从 Vue 前端讲到 Spring Boot 后端:模板、组件、路由、axios、Controller、JPA、文件上传、Nginx 部署,最后完成学习平台实训。10 章 71 节,配 220 张操作截图与可直接运行的代码。