企业级-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中一切皆对象:深入理解Python的对象模型
开发语言·python·程序人生·个人开发
梵得儿SHI8 分钟前
Vue 核心语法之组件基础与通信:从创建到注册的完整指南
前端·javascript·vue.js·组件化开发·全局注册·vue组件的本质·局部注册和异步组件
MQliferecord21 分钟前
如何快速实现响应式多屏幕适配
前端
韭菜炒大葱24 分钟前
从回调到async/await:JavaScript异步编程的进化之路
前端·javascript·面试
凌晨起床25 分钟前
前端开发规范
前端
烤汉堡35 分钟前
Python入门到实战:post请求和响应
python·html
Cache技术分享36 分钟前
247. Java 集合 - 为什么要远离 Stack 类?
前端·后端
v***91301 小时前
Spring+Quartz实现定时任务的配置方法
android·前端·后端
charlie1145141911 小时前
面向C++程序员的JavaScript 语法实战学习4
开发语言·前端·javascript·学习·函数
夫唯不争,故无尤也1 小时前
Python广播机制:张量的影分身术
开发语言·python