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

三、总结

简洁、高效、易用!

相关推荐
摩尔曼斯克的海6 分钟前
力扣面试题--双指针类
python·算法·leetcode
witAI6 分钟前
gemini3.1拆短剧2025解析,多模态模型如何重塑内容创作流程
人工智能·python
XPoet7 分钟前
AI 编程工程化:Rule——给你的 AI 员工立规矩
前端·后端·ai编程
热爱生活的五柒11 分钟前
解决 npm install 一直在转圈的问题
前端·npm·node.js
love530love16 分钟前
Windows 11 源码编译 vLLM 0.16 完全指南(CUDA 12.6 / PyTorch 2.7.1+cu126)
人工智能·pytorch·windows·python·深度学习·comfyui·vllm
zach01271 小时前
GEO优化的算力贫困悖论:基于数字地缘政治的量子搜索语义重构
人工智能·python·重构
xuansec1 小时前
【Web攻防】文件与目录安全漏洞详解:下载/删除/遍历/穿越实操指南
前端
Beginner x_u1 小时前
CSS 动画体系(二)—— Animation关键帧动画
前端·css·animation
T-shmily1 小时前
CSS Grid 网格布局(display: grid)全解析
前端·css
AsDuang2 小时前
Python 3.12 MagicMethods - 28 - __rsub__
开发语言·python