如果你在使用 response.getOutputStream() 方法時出現(xiàn) getOutputStream() has already been called for this response 錯誤,通常是由于多次嘗試獲取輸出流所導致的。
在一個 HTTP 響應中,只能獲取一次輸出流,否則就會拋出上述錯誤。這是因為獲取輸出流時實際上已經(jīng)開始了 HTTP 響應的正文部分,如果再次嘗試獲取輸出流,就會導致輸出流被關閉或刷新,從而引發(fā)錯誤。
為了解決這個問題,你可以嘗試按照以下方式來修改你的代碼:
1、確保你只獲取一次輸出流,并在需要使用輸出流的位置傳遞或引用該輸出流。如果你需要多次使用輸出流,可以使用 ByteArrayOutputStream 類型的中間緩存,先將數(shù)據(jù)寫入緩存中,最后再一次性輸出。
2、在調(diào)用 wb.write(response.getOutputStream()) 方法之前,確認輸出流是否已經(jīng)被關閉或刷新,可以使用 response.isCommitted() 方法來檢查,如果已經(jīng)被關閉或刷新,可以嘗試重新獲取輸出流或者使用其他方式輸出數(shù)據(jù)。文章來源:http://www.zghlxwxcb.cn/news/detail-755308.html
3、確認在調(diào)用 response.getOutputStream() 方法之前沒有其他輸出操作,否則可能會導致輸出流被關閉或刷新。你可以嘗試將這些輸出操作移動到獲取輸出流之后執(zhí)行。文章來源地址http://www.zghlxwxcb.cn/news/detail-755308.html
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
wb.write(outputStream);
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + StringUtil.encodeDownloadFileName(request, filename + ".xls"));
response.setContentLength(outputStream.size());
ServletOutputStream servletOutputStream = response.getOutputStream();
outputStream.writeTo(servletOutputStream);
servletOutputStream.flush();
servletOutputStream.close();
outputStream.close();
到了這里,關于關于wb.write(response.getOutputStream()); 報錯getOutputStream() has already been called for this respons的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!