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. Docker for Mac 創建的dnsmasq容器連不上/不工作的問題2. css3 - 圖片等比例縮放3. html - css3中多列高度 統一4. javascript - 使用angular 的ui-sref 中出現了中文參數,點擊跳轉后瀏覽器的地址欄里出現轉義后的%AE....%a%45. css3 - 如何將網頁CSS背景圖高斯模糊且全屏顯示6. javascript - 一個賦值運算的問題7. css3 - animation屬性,safari瀏覽器不支持相關效果8. javascript - 求賜教:網易郵箱Web端模擬登錄看信的加密參數_ntes_nnid、_ntes_nuid9. css - jq有無現成函數改變rotateX/Y的deg10. javascript - QWebEngineView 如何爬 angular 的動態數據?
