当前位置:   article > 正文

Springboot 解决linux服务器下获取不到项目Resources下资源_springboot linux getresource不能用

springboot linux getresource不能用

背景

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. }

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/815971
推荐阅读
相关标签
  

闽ICP备14008679号