【发布时间】:2026-01-25 07:50:01
【问题描述】:
需要帮助,
我正在努力在 Java Servlet 中下载文件,文件下载后无法将请求发送到页面。
当我尝试将请求转发到页面时,文件已成功下载并获得了非法状态异常。
这里是代码
public void fileDownload(String stringFileToDownload, HttpServletResponse response) throws Exception{
FileInputStream inStream = null;
OutputStream outStream = null;
try{
File downloadFile = new File(stringFileToDownload); //Reads input file
inStream = new FileInputStream(downloadFile);
response.setContentType("application/zip-compressed"); //MIME type of the file
response.setContentLength((int) downloadFile.length());
response.setHeader("Content-Disposition", "attachment; filename=Time.zip");
//response's output stream
outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
}
catch(Exception ex){
throw ex;
}
finally{
//response.flushBuffer();
try{
if(inStream != null){
inStream.close();
}
if(outStream != null){
//outStream.flush();
outStream.close();
}
}
catch(Exception ex){
throw ex;
}
}
}
我从 servlet 调用了这个方法;从 servlet 重定向到另一个页面
调用代码:
FileDownloadFromWeb fileDownloadFromWeb = new FileDownloadFromWeb();
fileDownloadFromWeb.fileDownload(stringarchiveFile, response); //Allow to download
Request Dispatcher objRequestDispatcher = request.getRequestDispatcher(objProperties.getProperty("SUCCESS_DOWNLOAD"));
objRequestDispatcher.forward(request, response);
【问题讨论】:
-
请出示调用代码。
-
该消息表示您尝试重定向,但您之前确实写了一些输出,这是不允许的
-
不进行任何写入活动。这是调用代码
FileDownloadFromWeb fileDownloadFromWeb = new FileDownloadFromWeb(); fileDownloadFromWeb.fileDownload(stringarchiveFile, response); //Allow to download //Request Dispatcher objRequestDispatcher = request.getRequestDispatcher(objProperties.getProperty("SUCCESS_DOWNLOAD")); objRequestDispatcher.forward(request, response);
标签: java file servlets tomcat8 download