java - jsp+springMVC實(shí)現(xiàn)文件下載的時(shí)候后臺拋出getOutputStream()異常
問題描述
使用JSP+springMVC框架做的web平臺,在做文件下載的時(shí)候,遇到這樣的問題:
文件下載部分的代碼是這樣寫的:
@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);//重新設(shè)置響應(yīng)頭文件字段,設(shè)置下載文件的文件名 OutputStream OutputStream = null; FileInputStream fileInputStream = null; try {OutputStream = response.getOutputStream();fileInputStream = new FileInputStream(filePath+fileName);byte[] buffer = new byte[1024*10];//設(shè)置文件大小上限為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對象進(jìn)行clear()和close()操作的,根本沒有針對后臺操作遇到的相同問題的解決方案,求大神指導(dǎo)。
問題解答
回答1:問題解決:把方法的返回類型改為void即可,猜測問題的原因可能是當(dāng)返回類型為String的時(shí)候,點(diǎn)擊下載按鈕,彈出下載頁面,這時(shí)候后臺代碼被中斷,沒有就行close();
相關(guān)文章:
1. python - pyspider的分布式運(yùn)行成功,2臺slave跑,但是時(shí)間并沒有縮短問題?2. 致命錯(cuò)誤: Class ’appfacadeTest’ not found3. dockerfile - 為什么docker容器啟動(dòng)不了?4. angular.js - 用requireJS模塊angularjs代碼時(shí)遇到一些問題5. android - Apk 中找不到r類文件6. npm install -g browser-sync這個(gè)之后出錯(cuò) 還有人嗎 我都感覺沒人回答問題了7. python - 數(shù)據(jù)無法插入到mysql表里8. javascript - 小程序跳轉(zhuǎn)失敗?9. javascript - 求正則表達(dá)式的寫法10. java - Oracle如何獲取去重結(jié)果集中某一條數(shù)據(jù)的下一條數(shù)據(jù)
