Spring Boot upload files / Picture & Picture display

First, the article Introduction

1. This article focuses on how to upload files under spring boot, especially upload pictures and displays, for example, when a user registered to upload a picture, then picture will be loaded on top of the registration page, when in Spring MVC, so to achieve better achieve, but to the Spring Boot just not the case

2. Small partners also found in use to deploy Tomcat server in the form of projects, upload to upload pictures directly to the Tomcat server can access, but in Spring Boot, the embedded Tomcat, every time a start the new Tomcat, location is not fixed

3. So it raises the question, first uploaded to the Tomcat, can access, but a restart project, Game Over

4. Therefore, under this article and we will study together, how to specify file upload path and access path resources in Spring Boot, so that you can save the picture and separate project alone management

The article mainly use Spring Boot & Thymeleaf & Maven to demonstrate, not Thymeleaf friends do not worry, things with very little, and almost JSP

Second, build environment

2.1 Spring Boot static resource access

1. Normal project js, css, gif, html, xml, avi and other files are considered static resources, access to static resources mainly in two ways: Spring Boot agreed directory, specify a static resource own path

2. Spring Boot directory has agreed four, according to the storage path convention, four default directory will put the src / main / resources in

  • META-INF/resources
  • resources
  • static
  • public
  • Priority: META-INF / resources> resources> static> public

3. We usually put in static, but in general, like pictures, videos and other resources are stored separately, so often need to specify a static resource access path

4. The custom path we need to implement WebMvcConfigurer interface and then override addResourceHandlers way to add resources to map the path, you need to call addResourceHandler registry of ( "/ **") addResourceLocations. ( "Classpath: / path /") to complete the mapping add (for this interface is not familiar friend recommended to study under, this article is primarily a file upload, this will not be an excuse to do in detail), after the completion of our own can be mapped to a resource directory path

5. Upload file MultipartFile mainly used to complete the class, so the two core file upload is MultipartFile classes and interfaces WebMvcConfigurer

2.2 Spring Boot environment to build

1. With these simple understanding, we now begin to build Spring Boot environment, the environment created primarily IDEA + Spring Initializr, I believe have seen this document, I believe that creating a project and basic skills, without further ado into the topic

2. Create complete we need to add Thymeleaf dependent, if another template engine, adding according to their own circumstances

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

3. Open application.properties configuration file (if you are yml few simple change on the line), we configured four content in the configuration file

  • Modify Tomcat port (optional, default 8080)
  • Placed Thymeleaf
  • Configure Spring MVC
  • Configuration file path (configuration in the configuration file is better than a dead code to write)

The third point of our application.properties configured as follows

  • user.file.path = directory you want to save the file, the default do not forget / or \\
    user.file.name = file upload name, true project can be dynamically generated, write here to demonstrate the dead
配置Thymeleaf,模式、编码、不使用缓存
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
  • Spring MVC view configuration, I believe we are very familiar with, go directly
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html
# 修改服务器端口
server.port=8888
# Thymeleaf
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
# Spring MVC
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html
# 文件路径, 注意路径末尾一定要带上/
user.file.path=F:/img/
user.file.name=springboot.jpg

5. Once you have configured the simple framework of the project has been considered above, we took classes start implementing

Third, the front-end interface

1. Form front-end interface is relatively simple, it shows a picture of the img tag and upload a file

2. 注意Thymeleaf中html文件需要方法resources的templates目录下,文件名index.html就行

3. 编写HTML

  • 在HTML标签上引入thymeleaf的名称空间:xmlns:th="http://www.thymeleaf.org"
  • 编写img标签,使用th语法指定img的资源路径:<img th:src="${filePath}">
  • 编写上传表单:这里比较简单,就不做介绍了,注意的是input为file的name需要记录,因为这个name必须要和控制器中MultipartFile的变量名相同,如果不同需要使用@RequestParam("file上传标签的name值")指定,截图和源码分别如下

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <img th:src="${filePath}">
    <form action="upload" method="post" enctype="multipart/form-data">
        <input type="file" name="pic">
        <input type="submit">
    </form>
</body>
</html>

4. 简单启动项目,输入访问地址就可以看到下面简陋的东西~~

四、上传实现

1. 上传文件建立一个controller,把我们配置文件中指定的文件名和路径使用@Value注解注入进来

2. 在方法参数中指定MultipartFile,注意返回值使用了ModelAndView是为了图片显示的时候将值回传回去

  • 参数为@RequestParam("pic") MultipartFile multipartFile 或者 MultipartFile pic,注意这个pic和表单中的文件标签的name值一样
  • 创建一个文件File file = new File(filePath + multipartFile.getOriginalFilename());
  • 调用MultipartFile 的multipartFile.transferTo(file)保存文件即可,是不是很简单

/**
 * 上传文件控制器
 *
 * @param multipartFile 文件上传类
 * @return ModelAndView
 */
@RequestMapping("/upload")
public ModelAndView update(@RequestParam("pic") MultipartFile multipartFile) {

	try {
		// 保存图片
		File file = new File(filePath + multipartFile.getOriginalFilename());
		multipartFile.transferTo(file);
	} catch (IOException e) {
		e.printStackTrace();
	}

	ModelAndView modelAndView = new ModelAndView();
	modelAndView.setViewName("index");

	return modelAndView;
}

3. 启动项目,我们测试一下文件上传(此时还是文件上传,并非图片显示),选择文件,然后提交,比如此处上传一个Redis-Docker的脚本,上传完成后可以在配置文件中指定的目录下看到该文件证明上传成功,文件上传没有问题就开始上传图片并显示

 

五、显示实现

5.1 控制器方式实现

1. 控制器方式实现其实就是为图片格式指定一个请求,每次加载都请求类,/{filename:.+}是指定路径变量配货图片如xx.png格式这个请求,resourceLoader.getResource("file:" + Paths.get(filePath + filename))); 中的 "file:"开头的代表使用file此种类型去加载这个资源,因为HTML是不能直接访问本地资源的,需要将本地资源放到file类型告诉HTML这个可以访问

@RequestMapping(value = "/{filename:.+}")
@ResponseBody
public ResponseEntity<?> getFile(@PathVariable String filename) {
	try {
		return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(filePath + filename)));
	} catch (Exception e) {
		return ResponseEntity.notFound().build();
	}
}

2. 配置好之后在之前写的upload上传控制器中加入一项 modelAndView.getModel().put("filePath", "/" + fileName); filePath是给img标签中的thymeleaf加载使用的,包含了图片的路径,这里指定了“/”是指在项目根目录加载资源

3. 重新启动项目,运行选择一张图片上传就可以看到文件上传收可以显示

4. 但是这种方式不太喜欢,因为有可能有别的请求误请求到此请求上,所以推荐使用5.2的配置方式

5.2 配置方式实现(推荐)

1. 配置方式就是实现WebMvcConfigurer, 将配置文件中文件路径也当做项目的的静态资源路径,同内置的static、public约定文件夹一样,配置注意一下两个事项

  • 项目中的资源是使用classpath:/开头,而本地文件夹需要使用file:/ 开头,使用文件协议加载文件
  • 结尾一定要有/或者\\,推荐使用/,如果不加没效果
  • 配置截图和源码如下

@Component
public class CustomWebConfiguration implements WebMvcConfigurer {
    @Value("${user.file.path}")
    private String filePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        // 注意如果filePath是写死在这里,一定不要忘记尾部的/或者\\,这样才能读取其目录下的文件
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/META-INF/resources/",
                "classpath:/resources/",
                "classpath:/static/",
                "classpath:/public/",
                "file:/" + filePath,
                "classpath:/webapp/");
    }
}

2. 重新启动项目,上传图片名称为springboot.jpg的文件,可以自己在配置文件该,这里只是演示,然后就可以看到下面的效果,controller配置和此处配置选其一即可,推荐使用配置

3. 来一张动图

六、项目源码

项目源码放到了百度云盘,方便大家下载:

链接: https://pan.baidu.com/s/1Vh9b6ZKs5KzR4f6ltIX4oA 提取码: ww5x

有问题欢迎留言大家一起探讨学习

发布了118 篇原创文章 · 获赞 1115 · 访问量 213万+

Guess you like

Origin blog.csdn.net/sinat_34104446/article/details/100178488