Spring Boot 处理文件上传及映射路径

Posted issue是fw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot 处理文件上传及映射路径相关的知识,希望对你有一定的参考价值。

样例代码

-------------

先编写一个文件上传页面/static/upload-test.html

请求路径为/upload

其中enctype=multipart/form-data是将文件以二进制的形式上传,这样可以实现多种类型的文件上传。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Spring Boot 文件上传测试</title>
  </head>
  <body>
    <form action="/upload" method="post" enctype="multipart/form-data">
      <input type="file" name="file" />
      <input type="submit" value="文件上传" />
    </form>
  </body>
</html>

新建文件上传处理 Controller

c o n t r o l l e r \\rm controller controller 包下新建 U p l o a d C o n t r o l l e r \\rm UploadController UploadController 并编写实际的文件上传逻辑代码,代码如下:

@Controller
public class UploadController 

    private final static String FILE_UPLOAD_PATH = "D:\\\\bigdata\\\\90809\\\\lou-springboot\\\\src\\\\main\\\\resources\\\\upload\\\\";

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) 
        if (file.isEmpty()) 
            return "上传失败";
        
        String fileName = file.getOriginalFilename();//获取文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));//获取文件后缀
        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");//指定日期格式
        Random r = new Random();//以当前时间为种子,创建一个随机数生成器
        StringBuilder tempName = new StringBuilder();//调用内置函数(append,insert等)用于拼接字符串的对象,和+操作没什么区别
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        try 
            // 保存文件
            byte[] bytes = file.getBytes();
            Path path = Paths.get(FILE_UPLOAD_PATH + newFileName);
            Files.write(path, bytes);

         catch (IOException e) 
            e.printStackTrace();
        
        return "上传成功,图片地址为:/files/" + newFileName;
    

成功上传!!

文件上传路径回显

上面虽然已经上传成功,但用户却不能通过路径访问(upload不是默认静态资源文件夹)

为了解决这个问题可以添加一个配置类来映射路径

package com.lou.springboot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SpringBootWebMvcConfigurer implements WebMvcConfigurer 
    public void addResourceHandlers(ResourceHandlerRegistry registry) 
//这样所有以files开头的请求都被视为请求上传的文件,映射到真正的路径上去
        registry.addResourceHandler("/files/**").addResourceLocations("file:D:/bigdata/90809/lou-springboot/src/main/resources/upload/");
    


以上是关于Spring Boot 处理文件上传及映射路径的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 嵌入式 Tomcat 文件上传url 映射虚拟路径

spring boot文件路径映射配置

Spring Boot 上传文件 获取项目根路径 物理地址 resttemplate上传文件

spring 文件上传

spring boot 下 mapper接口与xml文件映射问题

Spring Boot 中的文件上传:上传、验证和异常处理