java加载远程服务器上的文件、文件名包含中文
由于在项目中,不想把文件的存储路径暴露到前端,所以采用了stream的方式将文件输入到前端。
项目初始阶段,没有考虑到NAS存储保存图片到另外一台服务器上,所以采用了最近简单的写法。但是发布到正式环境以后,图片死活显示不出来,一直以为是被其他的安全软件拦击了。
PS:易错点
1、不要相信“File.separator”,
在Windows下是"\",在linux下是“/”
但是在拼接路径的时候,需要用的是“/”,而不是“\”
2、远程服务器上的图片,不能通过路径直接 new FileInputStream,需要通过URL对象访问
3、远程路径拼接时,如果存在中文,需要用 URLEncoder.encode(fileName, "utf-8") 包一下
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); } }
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(); } } }