企业级-PDF文件下载

作者:fyupeng
技术专栏:☞ https://github.com/fyupeng
项目地址:☞ https://github.com/fyupeng/rpc-netty-framework


留给读者

一、介绍

文件下载在浏览器可以根据响应头设置纯下载和直接打开两种方式。

二、代码


@RequestMapping("/downloadPdf")
	@ResponseBody
	public void downloadSignPdf(HttpServletRequest request, HttpServletResponse response) {


		OutputStream out = null;
		try {
			byte[] bytes = docService.downLoadPdf(gid, type, isHs);
			if (bytes == null) {
				// 构造错误信息的 JSON 格式字符串
				String errorMsg = "{\"msg\": \"文件不存在\", \"gid\": \""+gid+"\", \"type\": \""+type+"\", \"isHs\": \""+isHs+"\" }";
				// 设置响应的 Content-Type 和字符编码
				response.setContentType("application/json;charset=UTF-8");
				// 将错误信息写入响应输出流
				PrintWriter pw = response.getWriter();
				pw.print(errorMsg);
				pw.flush();
				return;
			}
			response.reset(); // 非常重要
			// 纯下载方式
			//response.setContentType("text/html; charset=UTF-8");
			//response.setHeader("Content-Disposition", "attachment;fileName=" + gid + ".pdf");
			// 直接打开
			response.setContentType("application/pdf"); // 设置返回的文件类型
			response.addHeader("Content-Length", String.valueOf(bytes.length));  //文件大小

			out = response.getOutputStream();
			out.write(bytes);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("下载电子签名后的pdf失败,gid={}, type={}, isHs={}", gid, type, isHs);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

三、总结

简洁、高效、易用!

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嗝屁小孩纸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值