自我记录 自我记录。。
源码下载地址:https://download.youkuaiyun.com/download/privatechen/10463674
之前用tomcat上传以及获取图片,图片的上传一般是放在tomcat中,项目中的文件夹下,但是当使用springboot打成的jar包时,此时上传图片便不能直接传入项目的根文件夹中了,因为整个项目打成了一jar包,不可拆分,此时,可以将图片传输到项目之外的文件夹下。
这里记录下如何将图片传送到springboot项目之外的文件夹下,并且如何从该文件夹下获取图片并展示到界面上
上传
上传这个比较简单,springboot官网上就有示例可用,这里更精简一下,这个例子里只有四个文件:
1、启动类
@SpringBootApplication
(exclude = {DataSourceAutoConfiguration.class})
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
2、Controller
@Controller
public class FileUploadController {
// 这里的是application.properties中配置的地址
@Value("${uploadpic.path}")
private String uploadPicPath;
// 主界面
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("messages", "cpxxxxx");
return "uploadPic";
}
// 文件上传按钮action
@PostMapping("/uploadPic")
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes, Model model) throws Exception {
// 存储图片到本地
storePic(file);
redirectAttributes.addFlashAttribute("message", "成功上传" + file.getOriginalFilename() + "!");
System.out.println("上传的文件名字:" + file.getOriginalFilename());
model.addAttribute("picName", file.getOriginalFilename()); // 将文件传输成功之后的名字传回界面,用于展示图片
return "uploadPic";
}
private String storePic(MultipartFile file) throws Exception {
String filename = StringUtils.cleanPath(file.getOriginalFilename());
try {
try (InputStream inputStream = file.getInputStream()) {
Files.copy(inputStream, Paths.get(uploadPicPath + filename), // 这里指定了下载的位置
StandardCopyOption.REPLACE_EXISTING);
}
}
catch (IOException e) {
throw new Exception("失败!" + filename, e);
}
return filename;
}
}
3、界面
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
<div>
<form method="POST" enctype="multipart/form-data" action="/uploadPic"> <!--这里可以限制文件后缀-->
<table>
<tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
<tr><td></td><td><input type="submit" value="Upload" /></td></tr>
</table>
</form>
</div>
<div>
此处展示上传后的图片:<img th:src="${picName}"/>
</div>
</body>
</html>
4、配置文件application.properties
server.port=11111
uploadpic.path = F:/uploadPic/
#这里这两个是关键,没有这两个配置,前台获取不到图片,映射路径到指定路径,这里是把localhost:11111路径映射到了F:/uploadPic/下
#界面上的图片路径如果为localhost:11111/abc.jpg 这个路径会映射到 F:/uploadPic/abc.jpg下
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=file:${uploadpic.path}
获取
在配置文件application.properties中加上这两句配置即可。。。其实上面的已经可以在界面获取到图片了,主要是映射问题
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=file:${uploadpic.path}