使用servlet下载大文件

0 java file-io servlets

我正在使用Apache Tomcat Server 6和Java 1.6,并试图将mp3大文件写入ServletOutputStream,以供用户下载。目前文件大小为50-750MB。

较小的文件不会引起太大的问题,但是较大的文件会导致套接字异常中断。

File fileMp3 = new File(objDownloadSong.getStrSongFolder() + "/" + strSongIdName);
FileInputStream fis = new FileInputStream(fileMp3);
response.setContentType("audio/mpeg");
response.setHeader("Content-Disposition", "attachment; filename=\"" + strSongName + ".mp3\";");
response.setContentLength((int) fileMp3.length());
OutputStream os = response.getOutputStream();

try {
    int byteRead = 0;
    while ((byteRead = fis.read()) != -1) {
        os.write(byteRead);
    }
    os.flush();
} catch (Exception excp) {
    downloadComplete = "-1";
    excp.printStackTrace();
} finally {
    os.close();
    fis.close();
}
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 5

但是对于较大的文件,似乎是将其写入堆中,然后导致OutOfMemory错误并导致整个服务器宕机

原因不在其他代码段中。原因之一是将整个文件读入一个byte[],但是在您发布的代码中似乎没有发生。另外,Tomcat 6默认情况下每2KB自动刷新响应流。将来也请在问题中包括整个stacktrace。它可能表明链中的a HttpServletResponseWrapper和/或a Filter可能正在缓冲整个响应。

也越来越套接字异常断开的管道。

这仅表示另一方已中止该请求。从服务器端不采取任何措施,从技术上讲也不应造成损害。您可以放心地忽略它。