我有一个只读取文件并将其发送到浏览器的servlet。 该文件已正确重新登录,但在OutputStream.flush()上,浏览器不会收到任何数据。
Firefox说: "损坏的内容错误 您尝试查看的页面无法显示,因为检测到数据传输错误。"。 Firebug显示状态" Aborted"。
IE打开或保存一个空文件。 我尝试过小文件或大文件。
代码是:
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Use a ServletOutputStream because we may pass binary information
response.reset();
OutputStream out = response.getOutputStream();
// Get the file to view
String file = request.getParameter("path");
// Get and set the type and size of the file
String contentType = getServletContext().getMimeType(file);
response.setContentType(contentType);
long fileSize = (new File(file)).length();
response.setHeader("Content-Length:", "" + fileSize);
File f = new File(file);
response.setHeader("Content-Disposition", "attachment;filename="+f.getName());
response.setContentLength((int) fileSize);
// Return the file
try {
returnFile(file, out, response);
} catch (Exception e) {
Logger.getLogger(AffichageItemsServlet.class).error("", e);
} finally {
out.close();
}
}
// Send the contents of the file to the output stream
public static void returnFile(String filename, OutputStream out, HttpServletResponse resp)
throws FileNotFoundException, IOException {
FileInputStream fis = null;
try {
fis = new FileInputStream(filename);
byte[] buff = new byte[8* 1024];
int nbRead = 0;
while ((nbRead = fis.read(buff, 0, buff.length)) !=-1) {
out.write(buff, 0, nbRead);
}
out.flush();
} finally {
if (fis != null) {
fis.close();
}
}
}
响应发送在&#34; out.flush&#34;。
有什么想法吗?
答案 0 :(得分:1)
首先,删除这一行(你在下面调用setContentLength()):
response.setHeader("Content-Length:", "" + fileSize);
此外,您可以尝试在开始使用流之前将getOutputStream()
调用移动。