前言(可跳)
上传图片并回显是项目中常见的功能之一;对于java的文件上传大家应该都接触过,无非是将文件以什么什么形式上传到某个文件夹中,所以重要的是将其回显。原本是想将他上传到项目中的/static/文件夹下,因为这个文件夹下的文件可以直接被springboot引用,但是想法是美好的,实际是残酷的,上传至这里并不能直接使用,除非上传一次图片将项目重新编译一次,便可直接引用,显然不现实。
步骤
View层
简单的HTML上传代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>file</title>
</head>
<body>
<form action="#" th:action="@{/upload}" method="post" enctype="multipart/form-data">
<label>上传图片</label>
<input type="file" name="file">
<input type="submit" value="上传">
</form>
<div th:text="${#strings.isEmpty(url)}"></div>
<div th:unless="${#strings.isEmpty(url)}">
<h1>图片</h1>
<img src="#" th:src="@{${url}}" alt="">
<h2>图片img显示</h2>
<img src="#" th:src="@{${path}}" alt="">
</div>
</body>
</html>
Controller层
正常的文件处理方法
import java.nio.file.Files;
/*
*created by mouse on 2020/2/29
*/
@Controller
public class UploadController {
@GetMapping("/file")
public String toFile(){
return "file";
}
@PostMapping("/upload")
public String Upload(@RequestParam(value = "file")MultipartFile file, RedirectAttributes attributes){
if (file.isEmpty()) {
System.out.println("文件为空");
}
// 上传的文件名称
String fileName = file.getOriginalFilename();
// 上传文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 上传至文件夹路径
String filePath = "src/main/resources/static/images/";
// 生成新的文件名
fileName = UUID.randomUUID()+suffixName;
// 保存方法一
/*
File uploadFile = new File(filePath + fileName);
if (!uploadFile.getParentFile().exists()) {
uploadFile.getParentFile().mkdirs();
}
try {
file.transferTo(uploadFile);
} catch (IOException e) {
e.printStackTrace();
}
*/
// 保存方法二
try {
byte[] bytes = file.getBytes();
Path p = Paths.get(filePath+fileName);
Files.write(p, bytes);
} catch (IOException e) {
e.printStackTrace();
}
// 回显本地资源地址
String url = "/file/" + fileName;
attributes.addFlashAttribute("url", url);
// 想法尝试直接static引用,不行
attributes.addFlashAttribute("path", "/images/"+fileName);
return "redirect:/file";
}
}
配置
使用Springboot提供的方法将上传的图片作为本地资源加载。
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/file/**").addResourceLocations("file:F:/project/study/src/main/resources/static/images/");
}
}
"/file/**"
是访问路径,与匹配形式,
"file:F:/project/study/src/main/resources/static/images/"
是本地文件所在文件夹