我有以下JSP代码来下载文件:
// reads input file from an absolute path
File downloadFile = new File(fullPath);
FileInputStream inStream = new FileInputStream(downloadFile);
// obtains ServletContext
ServletContext context = getServletContext();
// gets MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
out.println("MIME type: " + mimeType);
// modifies response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// forces download
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);
// obtains response's output stream
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inStream.close();
outStream.close();
out.println("<strong>" + sqlResults[1] + "</strong> records exported from " + fileType + " table.<br>");
当我运行此代码时,我会弹出一个让我选择目标目录的弹出窗口。单击“确定”后,文件将下载,浏览器将立即返回上一个屏幕(即调用此JSP代码的屏幕)。
浏览器不显示:
out.println("<strong>" + sqlResults[1] + "</strong> records exported from " + fileType + " table.<br>");
我的问题是:如何更正代码,以便在文件下载后立即在浏览器中显示此消息?