java使用浏览器请求下载pdf文件
代码
/**
* 下载pdf文件
*
* @param pdfFileUrl 文件地址
* @param fileName 文件名称
*/
public static void downloadPdf(String pdfFileUrl, String fileName) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
if (null == requestAttributes) {
throw new RuntimeException("请求失败");
}
HttpServletResponse response = requestAttributes.getResponse();
ServletOutputStream outputStream = null;
InputStream inputStream = null;
try {
// 获取网络文件
URL urlFile = new URL(pdfFileUrl);
HttpURLConnection conn = (HttpURLConnection) urlFile.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
// 通过输入流获取图片数据
inputStream = conn.getInputStream();
// 文件类型
response.setContentType("application/pdf");
// 设置请求头
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 获取输出流
outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while( (len = inputStream.read(buffer)) != -1 ){
outputStream.write(buffer, 0, len);
}
outputStream.flush();
} catch (Exception e) {
log.error("【下载PDF文件失败】原因:{}", e.getMessage());
e.printStackTrace();
} finally {
try {
if (null != inputStream) {
inputStream.close();
}
if (null != outputStream) {
outputStream.close();
}
} catch (Exception ignored) {}
}
}