pdf 配置预览
比较简单,直接上代码
@Resource
private IProductService productService;
@Value("${npi.default-url}")
private String domain;
@RequestMapping(value = "/preview", method = RequestMethod.GET)
@LogApi(value = "preview")
@ApiOperation(value = "预览文件", notes = "预览")
public void preview(@RequestParam("path") String path, @RequestParam("npiProductId") String npiProductId, HttpServletRequest request, HttpServletResponse response) throws IOException {
String username = JwtUtil.getUsername();
if (StringUtils.isEmpty(username)) {
String redirectPath = "/data-center/product-info/product-od-picture?action=preview&fileName=" + path + "&npiProductId=" + npiProductId;
response.sendRedirect(domain + redirectPath);
}
boolean validateDataAuthority = validateDataAuthority(npiProductId, request);
if (!validateDataAuthority) {
throw new BusinessException("you have no auth to view the file!");
}
preview(path, response);
}
private boolean validateDataAuthority(String npiProductId, HttpServletRequest request) {
if (StringUtils.isEmpty(npiProductId)) {
throw new BusinessException("npiProductId can not empty!");
}
List<Product> list = productService.getAuthProduct(request);
Optional<Product> first = list.stream().filter(product -> npiProductId.equals(product.getId())).findFirst();
if (first.isPresent()) {
return first.get().getHaveReadAuth();
}
return false;
}
private void preview(String path, HttpServletResponse response) {
try {
String filepath = springBootPlusProperties.getUploadPath() + path;
log.info("file path is ===> " + filepath);
File file = new File(filepath);
if (!file.exists()) {
response.sendError(404, "File not found!");
return;
}
previewWrapper(response, filepath, file);
} catch (Exception e) {
e.printStackTrace();
}
}
private void previewWrapper(HttpServletResponse response, String filepath, File file) throws IOException {
resetResponseHeader(response, filepath, file);
BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
byte[] bs = new byte[1024];
int len = 0;
OutputStream out = response.getOutputStream();
while ((len = br.read(bs)) > 0) {
out.write(bs, 0, len);
}
out.flush();
out.close();
br.close();
}
private void resetResponseHeader(HttpServletResponse response, String filepath, File file) throws IOException {
response.reset();
String filename = file.getName();
String suffix = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
if (ArrayUtil.contains(CommonConstant.PDF_TYPE, suffix)) {
URL u = new URL("file:///" + filepath);
String contentType = u.openConnection().getContentType();
response.setContentType(contentType);
response.setHeader("Content-Disposition", "inline;filename=" + filename);
} else {
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
}
}
|