java - jsp+springMVC实现文件下载的时候后台抛出getOutputStream()异常
问题描述
使用JSP+springMVC框架做的web平台,在做文件下载的时候,遇到这样的问题:
文件下载部分的代码是这样写的:
@RequestMapping('/ModelDownload{id}')public String ModelDownLoad(@PathVariable int id, HttpServletResponse response){ String fileName = 'download.txt'; String filePath = 'D:'; String modelName = new ModelService().getModelById(id).getModelName(); System.out.println(modelName); response.reset(); response.setContentType('application/x-download'); response.addHeader('Content-Disposition', 'attachment;filename='+fileName);//重新设置响应头文件字段,设置下载文件的文件名 OutputStream OutputStream = null; FileInputStream fileInputStream = null; try {OutputStream = response.getOutputStream();fileInputStream = new FileInputStream(filePath+fileName);byte[] buffer = new byte[1024*10];//设置文件大小上限为10Mfor (int read; (read = fileInputStream.read(buffer)) != -1;){ OutputStream.write(buffer,0,read);} } catch (IOException e) {// TODO Auto-generated catch blockSystem.out.println(e.toString()); } finally{try { fileInputStream.close(); OutputStream.close();} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace();} } return 'success';}
百度了很多,几乎都是说在JSP上使用out对象进行clear()和close()操作的,根本没有针对后台操作遇到的相同问题的解决方案,求大神指导。
问题解答
回答1:问题解决:把方法的返回类型改为void即可,猜测问题的原因可能是当返回类型为String的时候,点击下载按钮,弹出下载页面,这时候后台代码被中断,没有就行close();
相关文章:
1. html5和Flash对抗是什么情况?2. html - 内嵌app 的web 页面如何应用 app 内置的静态文件3. html5 - h5写的app用的webview,用手机浏览器打开不显示?4. java - C语言算法题-韩信点兵 求解?5. docker-compose 为何找不到配置文件?6. docker容器呢SSH为什么连不通呢?7. Whitelabel错误页面发生意外错误(类型=未找到,状态= 404)/WEB-INF/views/home.jsp8. 用Java8的 stream 操作外部集合是否存在并发问题?9. javascript - nodejs使用require(’request’)模块发送数据,报错10. javascript - 移动端,当出现遮罩层的时候,遮罩层里有div是超出高度scroll的,怎么避免滑动div的时候,body跟随滑动?
