spring-boot静态资源相关

一、在application.yml中配置静态文件映射

spring:
#  配置访问路径
  mvc:
    static-path-pattern: /**
#  配置静态资源位置
  web:
    resources:
      static-locations:
        - classpath:/static/

二、使用自动配置设置路径映射

package com.xia.xiatest.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 InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //    配置虚拟路径
        registry.addResourceHandler("/image/**").addResourceLocations("file:/tmp/image/");
    }
}

三、以附件形式下载文件

Content-Disposition:文件形式

attachment:附件形式下载

filename=bg.png:下载文件名

    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition","attachment; filename=bg.png");
        InputStream is = null;
        try {
            is = new ClassPathResource("static/logo.png").getInputStream();
            IoUtil.copy(is,response.getOutputStream());
        } finally {
            is.close();
        }
    }

IoUtil来自hutool。

猜你喜欢

转载自blog.csdn.net/qq_33235279/article/details/129491947