My problem is, I can't download files that are larger than 100mb and I suspect the html request

This is the setHeader from my response

HttpServletResponse response = (HttpServletResponse) requestContext.getExternalContext().getNativeResponse();
            response.setContentType("application/octet-stream");        
            response.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-control", "private");

And this is the stream declaration for read the file

ServletOutputStream sos = response.getOutputStream();   
                sos.flush();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String str = br.readLine();
                while (str != null) {                                           
                    sos.write(str.getBytes());
                    sos.write(13);
                    sos.write(10);
                    str = br.readLine();
                }

This 'while' works fine for small files but in case of large files, it seems as if the session was lost because I miss debug and does not stop at the next breakpoint. Is there any way to prevent the execution miss

有帮助吗?

解决方案

Every time flush the output stream object in the while loop after reading some data. you can set a long value and check. if that limit reaches you can flush the data in the output stream object, so that system will flushes that much amount of data and free the memory allocated for that so will not come the out of memory error.

ServletOutputStream sos = response.getOutputStream();
   long byteRead = 0;
   try {
       byte[] buf = new byte[8291];
       while (true) {
         int r = is.read(buf);
         if (r == -1)
         break;
         sos.write(buf, 0, r);
         byteRead +=r;
         if(byteRead > 1024*1024){ //flushes after 1mb
           byteRead = 0;
           sos.flush();
         }

      }
    } finally {
    if(sos != null){
      sos.flush();
    }
    try{is.close();}catch(Exception e){}
    try{sos.close();}catch(Exception e){}
 }

其他提示

Most likely the issue is that the byte data for an image won't have a newline and you are running out of memory trying to read a line. You need to create a buffer of a fixed size and copy the bytes directly. Something like this:

ServletOutputStream sos = response.getOutputStream();
sos.flush();
try {
    byte[] buf = new byte[1000];
    while (true) {
        int r = is.read(buf);
        if (r == -1)
            break;
        sos.write(buf, 0, r);
    }
} finally {
    try{is.close();}catch(Exception e){}
    try{sos.close();}catch(Exception e){}
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top