public void pdfdownload(HttpServletRequest request, HttpServletResponse response)
//实现返回文件下载功能
String fileName = "testout.pdf";//文件名
String fullPath = "D:Environment/testout.pdf";//文件本地路径
if (fullPath.contains("\\")) {
fullPath.replaceAll("\\\\","\\\\\\\\");
}
File f = new File(fullPath);
// 解决中文名称乱码问题
final String userAgent = request.getHeader("USER-AGENT");
if (userAgent.contains("MSIE")
|| userAgent.contains("Trident")
|| userAgent.contains("Edge")) { //IE浏览器
fileName = URLEncoder.encode(fileName, "UTF-8");
} else if (userAgent.contains("Mozilla")) { //google,火狐浏览器
fileName = new String(fileName.getBytes(), "ISO8859-1");
} else {
fileName = URLEncoder.encode(fileName, "UTF-8"); //其他浏览器
}
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attchement;filename=" + fileName );
try (FileInputStream fileInputStream = new FileInputStream(fullPath)) {
OutputStream outputStream = response.getOutputStream();
byte[] b = new byte[1024];
int j;
while ((j = fileInputStream.read(b)) > 0) {
outputStream.write(b, 0, j);
}
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.getMessage();
}
实现pdf文件返回到前端直接被下载
最新推荐文章于 2024-02-27 16:03:12 发布