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

三、总结

简洁、高效、易用!

相关推荐
Dolphin_海豚22 分钟前
electron windows 无边框窗口最大化时的隐藏边框问题
前端·electron·api
梦想CAD控件25 分钟前
WEB CAD与Mapbox结合实现在线地图和CAD编辑(CGCS2000)
前端·javascript·vue.js
screenCui1 小时前
macOS运行python程序遇libiomp5.dylib库冲突错误解决方案
开发语言·python·macos
AverageJoe19911 小时前
一次vite热更新不生效问题排查
前端·debug·vite
努力只为躺平1 小时前
🔥 油猴脚本开发指南:从基础API到发布全流程
前端·javascript
bitbitDown1 小时前
我用Playwright爬了掘金热榜,发现了这些有趣的秘密... 🕵️‍♂️
前端·javascript·vue.js
陈随易1 小时前
VSCode v1.102发布,AI体验大幅提升
前端·后端·程序员
小眼睛羊羊1 小时前
pyinstaller打包paddleocr
python
ma771 小时前
JavaScript 获取短链接原始地址的解决方案
前端