SpringMVC 设置 HttpServletResponse 下载,预览文件

该代码片段展示了如何使用Spring的@GetMapping注解从指定ID获取数据文件,并通过HttpServletResponse对象将其作为PDF文件提供给客户端下载。方法中包含了错误处理,并设置了响应头以触发文件下载而非预览。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	@GetMapping("/getDataFile/{id}")
    public void getAllData(@PathVariable("id") String id,HttpServletResponse response) {
        try {
            Object dataFile = service.getDataFile(id);
            byte[] byte = dataFile.getByte();
            download(byte,dataFile.getFileName(),response);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    public void download(byte[] buffer,String filename, HttpServletResponse response) {
        try {
            response.reset();

            // 设置response的Header 设置后会直接下载文件 而不是预览
            // response.addHeader("Content-Length", "" + buf.length);
            //response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

            //设置文件类型 参考 https://www.runoob.com/http/http-content-type.html
            response.setContentType("application/pdf");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值