SpringBoot 实现文件上传,图片上传并显示功能
我先看一下《颈椎病康复指南》再给大家说怎么实现的这两个功能,毕竟只是一个新手,解决这种复杂点的问题(相对而言),还是需要花费大量时间的,这篇文章花了两天的时间才实现的功能,现在就记录一下使用 springboot 怎么实现文件上传下载的。
我这里使用的是 springboot 2.0.3,不需要导入相关 jar 包,2.x 的版本已经整合进去了,直接使用即可。
spring 官网提供了 springboot 的文件上传下载案例,这是网址:https://spring.io/guides/gs/uploading-files/,使用的是流的输出,对于我这个新手来说,直接不理解,所以略过,通过网上查阅大量资料,终于把问题解决了。下面的案例是 springboot2.x 图片上传与回显。我使用的工具是 idea。
1、创建 idea 默认的 springboot 项目,我的版本是 2.0.3
2、创建一个控制层 FileController
package com.rainy.controller;import org.apache.catalina.servlet4preview.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;import java.io.*;import java.util.UUID;/*** 文件上传*/@Controllerpublic class FileController {@GetMapping(value = "/file")public String file() {return "file";}@PostMapping(value = "/fileUpload")public String fileUpload(@RequestParam(value = "file") MultipartFile file, Model model, HttpServletRequest request) {if (file.isEmpty()) {System.out.println("文件为空空");}String fileName = file.getOriginalFilename(); // 文件名String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 后缀名String filePath = "D://temp-rainy//"; // 上传后的路径fileName = UUID.randomUUID() + suffixName; // 新文件名File dest = new File(filePath + fileName);if (!dest.getParentFile().exists()) {dest.getParentFile().mkdirs();}try {file.transferTo(dest);} catch (IOException e) {e.printStackTrace();}String filename = "/temp-rainy/" + fileName;model.addAttribute("filename", filename);return "file";}}
3、创建 MyWebMvcConfigurer,这里是配置资源映射路径,详细点的介绍看这篇文章:/qq_38762237/article/details/81283241
/*** 资源映射路径*/@Configurationpublic class MyWebAppConfigurer implements WebMvcConfigurer {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/temp-rainy/**").addResourceLocations("file:D:/temp-rainy/");}}
4、jsp 页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>Title</title></head><body><form action="/fileUpload" method="post" enctype="multipart/form-data"><label>上传图片</label><input type="file" name="file"/><input type="submit" value="上传"/></form><p>图片:</p><img src="${filename }"/></body></html>
注意一点:我是使用 jsp 引擎来渲染,因为我不会用 Thymeleaf,添加 jsp 页面,springboot 使用 jsp 页面是需要进行配置 jsp 整合的,默认的是 Thymeleaf 的页面,简单的就是 HTML 页面
springboot 配置 jsp 页面的方法:/qq_38762237/article/details/81283352