springboot对外部资源文件的处理主要分为2部分,存和取,通过查看官方文件和看博客踩了坑之后终于搞定了,特此记录。
存方面倒还简单,这里贴上一个获取微信临时素材并保存的方法
/** * @功能 下载临时素材接口 * @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官方文档对静态资源这一块的表述
https://docs.spring.io/spring-boot/docs/1.5.19.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-static-content
主要使用到这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
随后网上查了一下,看到了这一篇https://blog.csdn.net/kilua_way/article/details/54601195
发现
spring.resources.static-locations= file:xxx
使用了file: + 路径这一配置方法,然后尝试了一下,变成这样:
spring: resources: static-locations: file:${my.config.static-location} my: config: static-location: /static/发现文件访问成功了!
所以实际上外部文件是需要file: 来配置的, static-locations默认访问的是类路径下的文件