spring boot 图片上传与显示功能实例详解

发布时间 - 2026-01-11 00:37:46    点击率:

首先描述一下问题,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 图片上传与显示功能实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!


# spring  # boot  # 图片上传  # 上传  # Spring Boot实现图片上传功能  # spring boot实现上传图片并在页面上显示及遇到的问题小结  # SpringBoot限制文件或图片上传大小的两种配置方法  # spring boot实现图片上传和下载功能  # spring boot thymeleaf 图片上传web项目根目录操作步骤  # 基于SpringBoot实现图片上传与显示  # bootstrap fileinput组件整合Springmvc上传图片到本地磁盘  # Spring boot的上传图片功能实例详解  # Spring Boot实现图片上传/加水印一把梭操作实例代码  # 小编  # 的是  # 加载  # 不可能  # 去了  # 在此  # 不是很  # 会在  # 不清楚  # 给大家  # 看完  # 相对于  # 方法来  # 所述  # 给我留言  # 不知怎么  # 感谢大家  # 要写  # 就可以 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 浅谈javascript alert和confirm的美化  魔方云NAT建站如何实现端口转发?  利用python获取某年中每个月的第一天和最后一天  Laravel怎么定时执行任务_Laravel任务调度器Schedule配置与Cron设置【教程】  Laravel如何使用查询构建器?(Query Builder高级用法)  Laravel如何使用Blade组件和插槽?(Component代码示例)  ChatGPT怎么生成Excel公式_ChatGPT公式生成方法【指南】  Laravel如何编写单元测试和功能测试?(PHPUnit示例)  HTML5空格和margin有啥区别_空格与外边距的使用场景【说明】  Laravel如何使用Blade模板引擎?(完整语法和示例)  Laravel如何实现图片防盗链功能_Laravel中间件验证Referer来源请求【方案】  如何选择可靠的免备案建站服务器?  如何在万网自助建站中设置域名及备案?  Laravel如何实现API版本控制_Laravel API版本化路由设计策略  动图在线制作网站有哪些,滑动动图图集怎么做?  Laravel如何使用Passport实现OAuth2?(完整配置步骤)  南京网站制作费用,南京远驱官方网站?  电商网站制作价格怎么算,网上拍卖流程以及规则?  佛山企业网站制作公司有哪些,沟通100网上服务官网?  Laravel如何安装Breeze扩展包_Laravel用户注册登录功能快速实现【流程】  个人摄影网站制作流程,摄影爱好者都去什么网站?  胶州企业网站制作公司,青岛石头网络科技有限公司怎么样?  大连 网站制作,大连天途有线官网?  Android使用GridView实现日历的简单功能  Laravel怎么实现API接口鉴权_Laravel Sanctum令牌生成与请求验证【教程】  利用vue写todolist单页应用  Laravel如何处理JSON字段的查询和更新_Laravel JSON列操作与查询技巧  微博html5版本怎么弄发语音微博_语音录制入口及时长限制操作【教程】  如何获取免费开源的自助建站系统源码?  高防服务器租用如何选择配置与防御等级?  Gemini手机端怎么发图片_Gemini手机端发图方法【步骤】  Laravel怎么进行浏览器测试_Laravel Dusk自动化浏览器测试入门  Laravel怎么连接多个数据库_Laravel多数据库连接配置  高端企业智能建站程序:SEO优化与响应式模板定制开发  Laravel怎么调用外部API_Laravel Http Client客户端使用  矢量图网站制作软件,用千图网的一张矢量图做公司app首页,该网站并未说明版权等问题,这样做算不算侵权?应该如何解决?  Laravel如何为API生成Swagger或OpenAPI文档  lovemo网页版地址 lovemo官网手机登录  网站制作价目表怎么做,珍爱网婚介费用多少?  jquery插件bootstrapValidator表单验证详解  Laravel模型事件有哪些_Laravel Model Event生命周期详解  Laravel如何处理JSON字段_Eloquent原生JSON字段类型操作教程  企业网站制作这些问题要关注  Laravel如何实现本地化和多语言支持_Laravel多语言配置与翻译文件管理  制作旅游网站html,怎样注册旅游网站?  如何注册花生壳免费域名并搭建个人网站?  桂林网站制作公司有哪些,桂林马拉松怎么报名?  如何在IIS中新建站点并解决端口绑定冲突?  如何制作一个表白网站视频,关于勇敢表白的小标题?  网站制作大概多少钱一个,做一个平台网站大概多少钱?