• Springboot 解决linux服务器下获取不到项目Resources下资源


    背景

    Springboot 项目中,我们获取Resources下资源,可以通过一般代码实现,但是当部署到linux服务器后,发现获取不了文件的路径,此时用下面的获取代码就可以完美解决。别忘记了加依赖哈。


    解决方案:

    依赖:

    1. <dependency>
    2. <groupId>commons-io</groupId>
    3. <artifactId>commons-io</artifactId>
    4. <version>2.7</version>
    5. </dependency>

    读取资源代码:

    1. public void getSignOutQrCode(String id, HttpServletResponse response) throws Exception {
    2. String text = QrCodeParamUtils.XFLL_QRCODE_1 + id + "_" + System.currentTimeMillis();
    3. //1.获取文件流
    4. InputStream stream = getClass().getClassLoader().getResourceAsStream("static/SignOut.png");
    5. //2.获取临时文件
    6. File file= new File("static/SignOut.png");
    7. try {
    8. //将读取到的类容存储到临时文件中,后面就可以用这个临时文件访问了
    9. FileUtils.copyInputStreamToFile(stream, file);
    10. } catch (Exception e) {
    11. log.error(e.getMessage());
    12. }
    13. //3.这个时候再去获取资源的文件路径 就可以正常获取了
    14. String filePath = file.getAbsolutePath();
    15. //String logoPath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "static/SignOut.png";
    16. QrCodeUtils.encode(text, filePath , response.getOutputStream(), true);
    17. }

    这样写就可以正常通过浏览器访问了。

  • 相关阅读:
    SpringMVC(三、JDBCTemplate和拦截器)
    应用程序日志管理工具
    探究Spring原理
    java-自定义数组的工具类
    mybatis动态SQL
    k8s 基于kubeadm搭建高可用集群
    Flowable主要API介绍
    09驾校科目一考试系统——提交分数
    获取泛型对应的类
    vue列表导出word文档
  • 原文地址:https://blog.csdn.net/qq_23126581/article/details/125424362