预览功能很简单,拿到文件流,写入到response中,设置一下contentType即完成。代码如下:
/** * 附件预览 * @param sysName 系统名称 * @param ym 年月 * @param attId 附件随机生成的id * @param response * @throws IOException */ @GetMapping(value = "/viewAttFile/{sysName}/{ym}/{attId}") public void viewAttFile(@PathVariable String sysName,@PathVariable String ym,@PathVariable String attId, HttpServletResponse response) throws IOException { LOGGER.debug(ImsConstants.ENTER_FUNCTION_THIRD_PARAM,sysName,ym, attId); response.setContentType("text/html; charset=UTF-8"); StringBuilder attIdSb=new StringBuilder(sysName).append("/").append(ym).append("/").append(attId); Path path = Paths.get(attIdSb.toString()); String contentType =Files.probeContentType(path); response.setContentType(contentType); FileStoreEntity entity = handler.getFileStore(attIdSb.toString(),attId); try (InputStream is = entity.getFsEntity().getInputstream(); OutputStream output = response.getOutputStream();) { IOUtil.copy(is, output); output.flush(); } }
值得注意的是contentType的获取,可以根据文件名称解析后得到,获取这个通用的方法花了不少功夫:
Path path = Paths.get(attIdSb.toString());
String contentType =Files.probeContentType(path);
大功告成,可以通过此预览txt,图片,pdf,各种资源文件了。