spring boot 图片上传与显示功能实例详解
作者:ohyeah-44 时间:2021-07-02 09:46:02
首先描述一下问题,spring boot 使用的是内嵌的tomcat, 所以不清楚文件上传到哪里去了, 而且spring boot 把静态的文件全部在启动的时候都会加载到classpath的目录下的,所以上传的文件不知相对于应用目录在哪,也不知怎么写访问路径合适,对于新手的自己真的一头雾水。
后面想起了官方的例子,没想到一开始被自己找到的官方例子,后面太依赖百度谷歌了,结果发现只有官方的例子能帮上忙,而且帮上大忙,直接上密码的代码
package hello;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class FileUploadController {
private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);
public static final String ROOT = "upload-dir";
private final ResourceLoader resourceLoader;
@Autowired
public FileUploadController(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@RequestMapping(method = RequestMethod.GET, value = "/")
public String provideUploadInfo(Model model) throws IOException {
model.addAttribute("files", Files.walk(Paths.get(ROOT))
.filter(path -> !path.equals(Paths.get(ROOT)))
.map(path -> Paths.get(ROOT).relativize(path))
.map(path -> linkTo(methodOn(FileUploadController.class).getFile(path.toString())).withRel(path.toString()))
.collect(Collectors.toList()));
return "uploadForm";
}
//显示图片的方法关键 匹配路径像 localhost:8080/b7c76eb3-5a67-4d41-ae5c-1642af3f8746.png
@RequestMapping(method = RequestMethod.GET, value = "/{filename:.+}")
@ResponseBody
public ResponseEntity<?> getFile(@PathVariable String filename) {
try {
return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()));
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
<strong>//上传的方法</strong>
@RequestMapping(method = RequestMethod.POST, value = "/")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes, HttpServletRequest request) {
System.out.println(request.getParameter("member"));
if (!file.isEmpty()) {
try {
Files.copy(file.getInputStream(), Paths.get(ROOT, file.getOriginalFilename()));
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
} catch (IOException|RuntimeException e) {
redirectAttributes.addFlashAttribute("message", "Failued to upload " + file.getOriginalFilename() + " => " + e.getMessage());
}
} else {
redirectAttributes.addFlashAttribute("message", "Failed to upload " + file.getOriginalFilename() + " because it was empty");
}
return "redirect:/";
}
}
看完上面的代码可以理解到spring boot 的存取文件思路了,存的时候的路径为
Paths.get(ROOT, filename).toString()))
这个路径会在本地的工程根目录上创建,不应用部署里的目录,所以一般的访问http访问不可能 ,所以它提供了ResourceLoader,利于这个类可以加载非应用目录的里文件然后返回
所以就可以读取文件,所以就要写getFIle方法来显示图片
如果大家对spring boot不是很了解,大家可以参考下面两篇文章。
Spring Boot 快速入门教程
Spring Boot 快速入门指南
以上所述是小编给大家介绍的spring boot 图片上传与显示功能实例详解网站的支持!
来源:http://blog.csdn.net/a625013/article/details/52414470
标签:spring,boot,上传
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java启用Azure Linux虚拟机诊断设置
2022-06-28 05:42:51
![](https://img.aspxhome.com/file/2023/8/78428_0s.png)
解决RedisTemplate存储至缓存数据出现乱码的情况
2023-04-20 15:30:58
![](https://img.aspxhome.com/file/2023/8/92718_0s.jpg)
JAVA 字符串加密、密码加密实现方法
2023-11-28 04:08:09
java map转Multipart/form-data类型body实例
2023-04-19 13:16:18
Java使用synchronized修饰方法来同步线程的实例演示
2022-11-29 18:33:29
java基础的详细了解第三天
2023-10-05 23:47:04
![](https://img.aspxhome.com/file/2023/9/84609_0s.png)
Android文本输入框(EditText)输入密码时显示与隐藏
2022-04-24 06:23:47
mybaties plus selectMaps和selectList的区别说明
2021-07-15 11:18:29
![](https://img.aspxhome.com/file/2023/5/68225_0s.png)
spring boot+vue 的前后端分离与合并方案实例详解
2023-08-20 10:41:07
![](https://img.aspxhome.com/file/2023/0/72580_0s.png)
c#委托详解和和示例分享
2022-10-26 12:29:41
![](https://img.aspxhome.com/file/2023/8/83238_0s.jpg)
Android 解决TextView排版参差不齐的问题
2022-06-25 06:43:30
基于Java+SpringBoot+Vue前后端分离实现仓库管理系统
2023-11-01 04:21:22
![](https://img.aspxhome.com/file/2023/1/99861_0s.jpg)
Java多线程run方法中直接调用service业务类应注意的问题及解决
2021-12-28 19:51:46
![](https://img.aspxhome.com/file/2023/0/92680_0s.png)
Android Loop机制中Looper与handler详细分析
2023-01-13 04:40:56
![](https://img.aspxhome.com/file/2023/3/90183_0s.png)
介绍java中Pair(配对)
2021-09-03 10:15:39
MAC算法之消息摘要算法HmacMD5的实现
2023-02-13 08:03:28
Java运算符的知识点与代码汇总
2022-12-05 19:03:36
如何安装系统认证签名过的APK
2023-07-24 21:35:40
SpringBoot深入分析讲解监听器模式上
2022-06-25 21:04:04
![](https://img.aspxhome.com/file/2023/3/62363_0s.png)
java增强for循环的实现方法
2023-12-07 16:42:53