企业级-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();
				}
			}
		}
	}

三、总结

简洁、高效、易用!

相关推荐
GIS之路1 天前
GDAL 实现矢量合并
前端
hxjhnct1 天前
React useContext的缺陷
前端·react.js·前端框架
清水白石0081 天前
解构异步编程的两种哲学:从 asyncio 到 Trio,理解 Nursery 的魔力
运维·服务器·数据库·python
山海青风1 天前
图像识别零基础实战入门 1 计算机如何“看”一张图片
图像处理·python
前端 贾公子1 天前
从入门到实践:前端 Monorepo 工程化实战(4)
前端
菩提小狗1 天前
Sqlmap双击运行脚本,双击直接打开。
前端·笔记·安全·web安全
彼岸花开了吗1 天前
构建AI智能体:八十、SVD知识整理与降维:从数据混沌到语义秩序的智能转换
人工智能·python·llm
前端工作日常1 天前
我学习到的AG-UI的概念
前端
韩师傅1 天前
前端开发消亡史:AI也无法掩盖没有设计创造力的真相
前端·人工智能·后端
山土成旧客1 天前
【Python学习打卡-Day40】从“能跑就行”到“工程标准”:PyTorch训练与测试的规范化写法
pytorch·python·学习