@GetMapping("/previewPDF")
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
String filePath = "G:\\JAVA\\xxx.pdf";
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "文件资源不存在!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] bs = new byte[1024];
int len;
response.reset(); // 非常重要
String fileName = "文件名称.pdf";
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = java.net.URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
} else {
//非IE浏览器:
fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
if (false) { // 是否在线预览
URL u = new URL("file:///" + filePath);
String contentType = u.openConnection().getContentType();
response.setContentType(contentType);
response.setHeader("Content-Disposition", "inline;filename=" + fileName);
// 文件名应该编码成utf-8,注意:使用时,我们可忽略这句
} else {
// 纯下载方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
}
OutputStream out = response.getOutputStream();
while ((len = br.read(bs)) > 0) {
out.write(bs, 0, len);
}
out.flush();
out.close();
br.close();
}
Java下载,预览pdf文件
最新推荐文章于 2024-06-04 20:12:16 发布