赞
踩
背景
Springboot 项目中,我们获取Resources下资源,可以通过一般代码实现,但是当部署到linux服务器后,发现获取不了文件的路径,此时用下面的获取代码就可以完美解决。别忘记了加依赖哈。
解决方案:
依赖:
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.7</version>
- </dependency>
读取资源代码:
- public void getSignOutQrCode(String id, HttpServletResponse response) throws Exception {
- String text = QrCodeParamUtils.XFLL_QRCODE_1 + id + "_" + System.currentTimeMillis();
- //1.获取文件流
- InputStream stream = getClass().getClassLoader().getResourceAsStream("static/SignOut.png");
- //2.获取临时文件
- File file= new File("static/SignOut.png");
- try {
- //将读取到的类容存储到临时文件中,后面就可以用这个临时文件访问了
- FileUtils.copyInputStreamToFile(stream, file);
- } catch (Exception e) {
- log.error(e.getMessage());
- }
- //3.这个时候再去获取资源的文件路径 就可以正常获取了
- String filePath = file.getAbsolutePath();
- //String logoPath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "static/SignOut.png";
- QrCodeUtils.encode(text, filePath , response.getOutputStream(), true);
- }

这样写就可以正常通过浏览器访问了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。