spring boot 设置访问静态资源 spring boot 2.5 配置访问本地文件

1.设置访问路

1. 设置访问路径与本地路径的映射在application.yml中

accessFile:
  resourceHandler: /show/**
  location: C:\home\

这里的home后面必须有"\"这个,如果不是顶级目录也可以没有

2.添加配置类

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${accessFile.resourceHandler}")
    private String resourceHandler; //匹配url 中的资源映射

    @Value("${accessFile.location}")
    private String location; //上传文件保存的本地目录

    /**
     * 配置静态资源映射
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //匹配到resourceHandler,将URL映射至location,也就是本地文件夹
        registry.addResourceHandler(resourceHandler).addResourceLocations("file:///" + location);
    }

}

这个配置类就是把show的路径映射到本地的、home文件夹下

3.重启项目

4.访问http:localhost:端口/show/访问的具体文件路径

这里的show 是上面yml中配置的

这里的具体文件路径是指的/home下的具体文件夹文件名

5。这里再加一个简单的文件上传

public int fileUpload(MultipartFile file){
        try {
            String filename = file.getOriginalFilename();
            System.out.println(filename);
            //根据相对路径获取绝对路径
            String realPath = "C:\\home\\img";
            file.transferTo(new File(realPath,filename));
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

 

6.再加一个修改springboot默认的上传文件大小

2.X

spring:
  servlet:
    multipart:
      max-file-size: 200MB # 设置文件大小
      max-request-size: 200MB #设置请求文件大小

1.5

spring.http.multipart.max-file-size=10MB

 

Guess you like

Origin blog.csdn.net/yu1xue1fei/article/details/117959234