首页 > 编程语言 > 使用springboot对外部静态资源文件的处理操作
2022
05-15

使用springboot对外部静态资源文件的处理操作

springboot对外部静态资源文件的处理

springboot对外部资源文件的处理主要分为2部分,存和取,通过查看官方文件和看博客踩了坑之后终于搞定了,特此记录。

1、存方面倒还简单,这里贴上一个获取微信临时素材并保存的方法

/**
     * @功能 下载临时素材接口
     * @param filePath 文件将要保存的目录
     * @param method 请求方法,包括POST和GET
     * @param url 请求的路径
     * @return
     */ 
    public static String saveUrlAs(String url,String filePath,String method){
        //创建不同的文件夹目录
        File file=new File(filePath);
        //判断文件夹是否存在
        if (!file.exists())
        {
            //如果文件夹不存在,则创建新的的文件夹
            file.mkdirs();
        }
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        String savePath = null ;
        try
        {
            // 建立链接
            URL httpUrl=new URL(url);
            conn=(HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单,默认get方式
            conn.setRequestMethod(method);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream=conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            //判断文件的保存路径后面是否以/结尾
            if (!filePath.endsWith("/")) { 
                filePath += "/"; 
            }
            String filePathDir =  DateUtil.getStringAllDate();
            //写入到文件(注意文件保存路径的后面一定要加上文件的名称)
            savePath = filePath+filePathDir+".png";
            fileOut = new FileOutputStream(savePath);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);
 
            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            //保存文件
            while(length != -1)
            {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
            conn.disconnect();
        } catch (Exception e)
        {
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>下载临时素材接口抛出异常 [{}]",e.getMessage());
        } 
        return savePath; 
    }

2、取,由于对springboot不熟悉,所以在这上面踩了坑

先看一下springboot官方文档对静态资源这一块的表述

主要使用到这2个配置

spring.mvc.static-path-pattern=/resources/**    //配置url访问路径
spring.resources.static-locations=                      //配置对应的文件路径

由于我想要将静态资源存到项目外部比如 和项目根目录同级的 static文件夹里,然后配置了

spring.resources.static-locations=  static/
spring.mvc.static-path-pattern=/static/** 

之后,访问文件一直404

随后网上查了一下,看到了一篇文章,发现

spring.resources.static-locations= file:xxx 

使用了file: + 路径这一配置方法,然后尝试了一下,变成这样:

spring:
  resources:
    static-locations: file:${my.config.static-location}
my:
  config:
    static-location: /static/

发现文件访问成功了!

所以实际上外部文件是需要file: 来配置的, static-locations默认访问的是类路径下的文件

SpringBoot2.x静态资源访问

问题

在springBoot1.5.x版本,访问静态资源直接访问static目录下的资源即可,不用带上static前缀,在2.x以上就失效了,现在记录下在2.x版本如何访问静态资源

开发环境:IDEA

文件目录:

  • templates存放官方推荐的thymeleaf模板
  • static存放静态资源

在controller目录下新建一个类,继承WebMvcConfigurationSupport,对静态资源目录说明

代码

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

原理

当访问的url中匹配到/static/**时,就去访问静态资源存放地static目录下寻找资源

在配置了静态资源路径后,就可以访问静态资源了,但是在访问时需要在路径前加上static

<a th:href="@{/static/imag1.jpg}" rel="external nofollow" >跳转</a>
<a th:href="@{/static/images/image2.jpg}" rel="external nofollow" >跳转</a>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持自学编程网。

编程技巧