2015-10-15 18 views
1

我有一个zip文件作为字节数组(byte []),我可以写使用的文件系统,爪哇 - 让字节数组作为下载

 FileOutputStream fos = new FileOutputStream("C:\\test1.zip"); 
     fos.write(decodedBytes); // decodedBytes is the zip file as a byte array 
     fos.close();    

相反,它写入文件和阅读它,使之作为一个下载,我想提出的字节数组作为一个直接下载, 我想这一点,

response.setContentType("application/zip"); 
    response.setHeader("Content-Disposition", "attachment; filename=\"File.zip\""); 
    ServletOutputStream outStream = response.getOutputStream(); 
    outStream.write(decodedBytes); // decodedBytes is the zip file as a byte array 

这不是工作,我得到空文件。如何将字节数组作为下载?

更新: 我添加finally子句并关闭了ServletOutputStream,它工作。

}catch (Exception e) { 
     Log.error(this, e); 
    } finally { 
     try{ 
      if (outStream != null) { 
       outStream.close();    
      } 
     } catch (IOException e) { 
      Log.error(this, "Download: Error during closing resources"); 
     } 
    } 

Pankaj解决方案也有效。

+0

检查此链接:http://stackoverflow.com/questions/13989215/how-to-convert-a-byte-into-a-file-with-a-download -dialog- –

+0

你确定'decodedBytes'实际上有数据吗?你有没有先试过_not_压缩数据? –

+0

@MattBall我在eclipse debug中检查了byte []的长度,它匹配物理zip文件。实际上byte []来自DB,它已经被压缩并存储在一个BLOB中。 – SyAu

回答

1

尝试以下操作:

ServletOutputStream outStream = response.getOutputStream(); 
response.setContentType("application/zip"); 
response.setHeader("Content-Disposition", "attachment; filename="DATA.ZIP""); 
outStream.write(decodedBytes); 
outStream.flush();