java加载远程服务器上的文件、文件名包含中文
由于在项目中,不想把文件的存储路径暴露到前端,所以采用了stream的方式将文件输入到前端。
项目初始阶段,没有考虑到NAS存储保存图片到另外一台服务器上,所以采用了最近简单的写法。但是发布到正式环境以后,图片死活显示不出来,一直以为是被其他的安全软件拦击了。
PS:易错点
1、不要相信“File.separator”,
在Windows下是"\",在linux下是“/”
但是在拼接路径的时候,需要用的是“/”,而不是“\”
2、远程服务器上的图片,不能通过路径直接 new FileInputStream,需要通过URL对象访问
3、远程路径拼接时,如果存在中文,需要用 URLEncoder.encode(fileName, "utf-8") 包一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | private InputStream getFileByName(String testId, String testCenterId, String taskId, String neeaAppId, String fileName) throws Exception { StringBuilder pathBuilder = new StringBuilder(); pathBuilder.append(projectProperties.getImgDirectory()); pathBuilder.append( "/" ); pathBuilder.append(testId); pathBuilder.append( "/" ); pathBuilder.append(testCenterId); pathBuilder.append( "/" ); pathBuilder.append(taskId); pathBuilder.append( "/" ); pathBuilder.append(neeaAppId); pathBuilder.append( "/" ); Pattern p = Pattern.compile(RegexConstant.HTTP_REGEX); Matcher m = p.matcher(projectProperties.getNosImgDirectory()); if (m.find()) { pathBuilder.append(URLEncoder.encode(fileName, "utf-8" )); String pathString = pathBuilder.toString(); log.info( "附件路径:" + pathString); //远程路径地址,需要采用url访问 URL url = new URL(pathString); return url.openStream(); } else { pathBuilder.append(fileName); String pathString = pathBuilder.toString(); log.info( "附件路径:" + pathString); return new FileInputStream(pathString); } }<br> |
public void loadImg( @RequestParam("testId") String testId, @RequestParam("testCenterId") String testCenterId, @RequestParam("taskId") String taskId, @RequestParam("neeaAppId") String neeaAppId, @RequestParam("file") String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception { OutputStream out = null; InputStream in = null; try { in = getFileByName(testId, testCenterId, taskId, neeaAppId, fileName); BufferedImage image = ImageIO.read(in); response.setContentType("image/jpeg"); out = response.getOutputStream(); if (image != null) { ImageIO.write(image, "jpeg", out); } } catch (IOException e) { log.error("获取图片异常{}", e.getMessage()); } finally { if (in != null) { in.close(); } if (out != null) { out.flush(); out.close(); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~