企业级-PDF文件下载

作者:fyupeng

技术专栏:☞ https://github.com/fyupeng

项目地址:☞ https://github.com/fyupeng/rpc-netty-framework


留给读者

一、介绍

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

二、代码

java 复制代码
@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();
				}
			}
		}
	}

三、总结

简洁、高效、易用!

相关推荐
Mr_Chenph4 分钟前
Qdrant Filtering:must / should / must_not 全解析(含 Python 实操)
python·filter·qdrant
GIS小小研究僧23 分钟前
免费PDF编辑软件 pdf24-creator 及其安装包
pdf
今夕节度使24 分钟前
Axure 11
python
Python当打之年27 分钟前
工具分享05 | Python制作PDF合并拆分提取工具V1.0
python·pdf
拾光拾趣录32 分钟前
基础 | 🔥6种声明方式全解⚠️
前端·面试
程序员黄同学1 小时前
Python 的列表 list 和元组 tuple 有啥本质区别?啥时候用谁更合适?
windows·python·list
万能程序员-传康Kk1 小时前
美团末端配送碳排放评估
python
朱程2 小时前
AI 编程时代手工匠人代码打造 React 项目实战(四):使用路由参数 & mock 接口数据
前端
PineappleCoder2 小时前
深入浅出React状态提升:告别组件间的"鸡同鸭讲"!
前端·react.js
wycode2 小时前
Vue2源码笔记(1)编译时-模板代码如何生效之生成AST树
前端·vue.js