SpringBoot 配置上传图片

本文介绍了如何在SpringBoot中配置图片上传功能。通过设置application.properties中的映射路径,结合WebAppConfiguration类中的addResourceHandler方法,实现本地路径与虚拟路径的映射。在前端,使用thymeleaf创建uploadPage.html,通过form表单提交图片。后端使用uploadController.java处理上传请求,以日期创建文件夹存储不同图片。

springBoot 配置上传图片

  • springBoot 上传图片涉及到虚拟路径与本地路径的配置:

    • springBoot 的配置文件: application.properties

      # 本都路径
      file.upload.path=F://JAVA学习/workspace/SpringBoot/images/   
      # 虚拟路径(映射路径)
      file.relative=/images/**
      
    • 配置映射路径类 WebAppConfiguration.java ,通过实现 WebMvcConfigurer 接口下的 addResourceHandler 方法,映射本地路径与虚拟路径。

      @Configuration
      public class MyWebAppConfigurer implements WebMvcConfigurer {
      
          @Value("${file.upload.path}")
          private String filePath; // 本地路径 localPath
      	
          @Value("${file.relative}")
          private String fileRelativaPath; // 虚拟路径,你也可以命名为 virtualPath
      
          @Override
          public void addResourceHandlers(ResourceHandlerRegistry registry) {
              registry.addResourceHandler(fileRelativaPath).addResourceLocations("file:" + filePath);
          }
      }
      
    • 编写前端的页面 uploadPage.html ,上传图片(这里用到的是 form 表单提交;也可以使用 ajax 异步实现)

      <!DOCTYPE html> <!--前端使用的是thymeleaf模板-->
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
          <meta charset="UTF-8">
          <title>图片上传</title>
      </head>
      <body>
      <form action="../upload" method="post" enctype="multipart/form-data">
          <input type="file" name="file" accept="image/*">
          <input type="submit" value="上传">
      </form>
      [[${filename}]]
      <br>
      <img th:src="@{${filename}}" alt="图片"/>
      </body>
      </html>
      
    • 随后编写后端的处理器 uploadController.java,用来接受并处理前端上传的图片数据,这里包括 以日期创建不同的文件夹 用于区分图片。

      @Controller
      public class uploadController {
      
          @Value("${file.upload.path}")
          private String filePath; // 获取文件上传的本地路径
      
          @GetMapping("/upTest")
          public String goUpload(){ // 跳转到图片上传页面
              return "imgUpload/imgUpload";
          }
      
          @PostMapping("/upload")
          public String upload(@RequestParam("file") MultipartFile file, Model model) throws IOException {
              // 获取图片上传的当天日期,创建文件
              String path = filePath + new SimpleDateFormat("yyyyMMdd").format(new Date());
              createDir(path);
              String fileName = file.getOriginalFilename();
              //上传
              // 生成新的文件名
              String realPath = path + "/" + UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));
              File dest = new File(realPath);
              // 判断文件父目录是否存在,即创建的是日期文件夹
              if (!dest.getParentFile().exists()) {
                  dest.getParentFile().mkdirs();
              }
              // 保存文件
              file.transferTo(dest);
              // 切割文件路径,获取图片的日期父目录
              String arr[] = dest.getParent().split("\\\\");
              System.out.println(arr[arr.length-1]);
              // 拼接后再传回前端
              model.addAttribute("filename", "/images/" + arr[arr.length-1] + "/" + dest.getName());
              return "imgUpload/imgUpload";
          }
      
          public static void createDir(String destDirName) {
              File dir = new File(destDirName);
              if (dir.exists()) {
                  return;
              }
              // endsWith() 判断字符串是否已指定后缀结尾,File.separator:间隔符‘/’
              if (!destDirName.endsWith(File.separator)) {
                  destDirName = destDirName + File.separator;
              }
              dir.mkdirs();
          }
      
      }
      
    • 结果:

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值