gpt4 book ai didi

java - 为什么调用 OutputStream.flush() 时我的浏览器没有收到数据?

转载 作者:太空宇宙 更新时间:2023-11-04 08:25:05 26 4
gpt4 key购买 nike

我有一个 servlet,它只读取文件并将其发送到浏览器。文件读取正确,但在 OutputStream.flush() 上,浏览器未收到任何数据。

火狐说:“内容损坏错误 由于检测到数据传输错误,无法显示您尝试查看的页面。”。Firebug 显示状态“已中止”。

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();
}
}
}

响应在“out.flush”上发送。

有什么想法吗?

最佳答案

首先,删除这一行(您在下面调用 setContentLength() ):

response.setHeader("Content-Length:", "" + fileSize);

此外,您可以尝试将 getOutputStream() 调用移至开始使用流之前。

关于java - 为什么调用 OutputStream.flush() 时我的浏览器没有收到数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8727736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com