java实现文件下载-问题踩坑:功能正常,控制台报错

关键字:

java,springboot,下载,上传,response,StackOverflow


问题描述:

报错信息(部分):Cannot forward to error page for request [/newsList] as the response has already been committed. As a result, the response may have the wrong status code.

用java做一个常规下载/预览功能时候,功能都可以正常实现,但是控制台会报错。一个是上面列的,另一个是StackOverflow。


原因分析:

目前具体原因未知,初步判断是框架获取HttpServletResponse原因,将参数获取方式改为servletRequestAttributes.getResponse()方式,问题解决。

解决方案:

问题代码

	@GetMapping("/download/{id}")
    public void download(@PathVariable Integer id, HttpServletResponse response) {
			
			response.setContentType("application/force-download");
            response.setContentType("multipart/form-data");
            // 设置文件名,attachment强制性下载
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
        
        //其他省略
        .....
}

修改后代码

	@GetMapping("/download/{id}")
    public void download(@PathVariable Integer id) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        
		response.setContentType("application/force-download");
        response.setContentType("multipart/form-data");
        // 设置文件名,attachment强制性下载
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
        
        //其他省略
        .....
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值