【问题标题】:Java - Make byte array as a downloadJava - 将字节数组作为下载
【发布时间】:2015-10-15 04:02:00
【问题描述】:

我有一个字节数组 (byte[]) 形式的 zip 文件,我可以使用它将其写入文件系统,

        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 解决方案也有效。

【问题讨论】:

  • 您确定decodedBytes 中确实有数据吗?您是否尝试过先压缩数据?
  • @MattBall 我在 Eclipse 调试中检查了 byte[] 的长度,它与物理 zip 文件匹配。实际上 byte[] 来自 DB,它已经被压缩并存储在一个 BLOB 中。
  • outStream.flush() 放在 outstream.write() 之后

标签: java java-6


【解决方案1】:

尝试以下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    相关资源
    最近更新 更多