spring boot 图片上传与显示功能实例详解
作者:ohyeah-44 发布时间:2021-07-02 09:46:02
标签:spring,boot,上传
首先描述一下问题,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


猜你喜欢
- 概要: ShardingSphere是一套开源的分布式数据库中间件解决方案组成的生态圈,它由Sharding-JDBC、Sharding-P
- 1、为什么使用Spring提供的JDBC的封装?因为Spring提供了完整的模板类以及基类可以简化开发,我们只需写少量的代码即可。2、实例讲
- ⭐️前面的话⭐️本篇文章带大家认识Java语法——泛型与通配符,泛型和通配符是一个非常抽象的概念,简
- java在jdk1.5中引入了注解,spring框架也正好把java注解发挥得淋漓尽致。下面会讲解Spring中自定义注解的简单流程,其中会
- 前言:封装、继承和多态是面向对象编程的三大特征。1.封装1.1.封装概念封装就是把抽象出的数据(属性)和对数据的操作(方法)封装在一起,数据
- file: BluetoothEventLoop.java GB/GB2/GB3: 1. import android.os.PowerMa
- 首先,定义TabHost的布局文件:<?xml version="1.0" encoding="utf-
- 最近有个需求 要求列表 滑动后第一条 需要和顶部对齐上网找了找 发现 官方支持 Recycle + LinearSna
- 策略模式也是一种非常常用的设计模式,而且也不复杂。下面我们就来看看这种模式。定义:策略模式定义了一系列的算法,并将每一个算法封装起来,而且使
- WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。WebSocket 使得客户端和服务器之间的数
- 题目一链表题——反转链表根据单链表的头节点head来返回反转后的链表具体题目如下解法/** * De
- 一、让ListView控件显示表头的方法在窗体中添加ListView 空间,其属性中设置:View属性设置为:Detail,Columns集
- Android 打开相册选择单张图片实现代码
- ProgressDialog 继承自AlertDialog,AlertDialog继承自Dialog,实现DialogInterface接口
- 快速排序是应用最广泛的排序算法,流行的原因是它实现简单,适用于各种不同情况的输入数据且在一般情况下比其他排序都快得多。快速排序是原地排序(只
- 1、什么是值传递,什么是引用传递?值传递(pass by value)是指在调用函数时将实际参数复制一份传递到函数中,这样在函数中如果对参数
- 1.Object类的equals()方法:比较两个对象是否是同一个对象,equals() 方法比较两个对象,是判断两个对象引用指向的是同一个
- 小编今天研究了在Unity3D中的数据持久化问题。数据持久化在任何一个开发领域都是一个值得关注的问题,小到一个应用中配置文件的读写,大到数据
- 本文实例讲述了C#交错数组用法。分享给大家供大家参考。具体分析如下:交错数组是数组的数组,交错数组的元素可以是不同的尺寸和大小。交错数组有时
- 本文实例为大家分享了ToolBar的使用方法,供大家参考,具体内容如下ToolBar时应用的标准工具栏;用来替代ActionBar;使用To