SpringBoot实现文件上传和以前操作是一样的,下来就简单的使用SpringBoot进行文件上传
- 导入依赖
在SpringBoot的web-starter中已经对SpringMVC文件上传有了引入,因此引入它就行,在后边演示用的是Thymeleaf因此也以同引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 编写文件上传资源映射器,用来隐藏我们真正的资源位置,也可以更好的管理项目
package com.wrial.bicyclesell.sell.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/show/image/**").addResourceLocations("classpath:/static/image/");
}
}
- 编写Controller进行简单的文件上传
package com.wrial.bicyclesell.sell.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Controller
public class UploadController {
public static String prefix = "http://localhost:8080/show/image/";
@RequestMapping("/toUpload")
public String toUpload(){
return "upload";
}
@PostMapping("/upload")
public String uploadFile(@PathVariable("file") MultipartFile file, Model model) {
//创建文件放在服务器端的位置
String path = "C:\\Users\\Administrator\\AppData\\Local\\Temp\\OnlineMall\\sell\\src\\main\\resources\\static\\image";
File fileDir = new File(path);
if (!fileDir.exists()) {
fileDir.mkdir();
}
//生成一个不重复的名字
String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String fileName = UUID.randomUUID().toString() + fileSuffix;
File file1 = new File(fileDir + "/" + fileName);
//上传
try {
file.transferTo(file1);
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
model.addAttribute("path",prefix+file1.getName());
return "upload";
}
}
- 编写一个简单的问价上传的HTML
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>文件上传</h2>
<hr>
<form method="post" enctype="multipart/form-data" action="/upload" th:if="${path==null}">
<p>
文件:<input type="file" name="file">
</p>
<p>
<input type="submit" value="上传">
</p>
</form>
<img th:if="${path!=null}" th:src="${path}">
</body>
</html>
这里存在一个问题,就是静态资源文件不能同步的刷新,必须手动在项目中重新build才能显示出上传的图片等,我想这就是dev-tool的长出所在吧,但是真正的生产环境都是由分布式文件上传服务器不会出现这种情况。