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

三、总结

简洁、高效、易用!

相关推荐
英宋2 分钟前
ckeditor5的研究 (2):对 CKEditor5 进行设计,并封装成一个可用的 vue 组件
前端·javascript
古夕2 分钟前
搞定滚动穿透
前端·javascript
英宋2 分钟前
ckeditor5的研究 (3):初步使用 CKEditor5 的 事件系统 和 API
前端·javascript
404.Not Found4 分钟前
Day46 Python打卡训练营
开发语言·python
love530love6 分钟前
【PyCharm必会基础】正确移除解释器及虚拟环境(以 Poetry 为例 )
开发语言·ide·windows·笔记·python·pycharm
lyc2333337 分钟前
鸿蒙多子类型输入法:3步实现输入模式自由切换🔤
前端
Danta7 分钟前
从 0 开始学习 Three.js(2)😁
前端·javascript·three.js
凌辰揽月8 分钟前
Web后端基础(基础知识)
java·开发语言·前端·数据库·学习·算法
Dignity_呱9 分钟前
vue3对组件通信做了哪些升级?
前端·vue.js·面试
植物系青年11 分钟前
基于 Lowcode Engine 的低码平台“编码效率”提升实践
前端·低代码