如何发送zip文件而不在物理位置创建它?

我想发送带有zip文件附件的电子邮件..我能够使用ByteArrayOutputStream发送pdf文件而不将它们保存在物理位置.但是当我尝试压缩那些文件时,发送它不起作用.它给予例外非法附件.

下面是我编写的用于创建zip的代码.

private MimeBodyPart zipAttachment( List<ByteArrayOutputStream> attachmentList, List<String> reportFileNames )
{
    MimeBodyPart messageBodyPart = null;
    try
    {
        // File file = File.createTempFile( "Reports.zip",".tmp" );
        // FileOutputStream fout = new FileOutputStream(file);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(attachmentList.size());
        ZipOutputStream zos = new ZipOutputStream( bout );
        ZipEntry entry;
        for( int i = 0; i < attachmentList.size(); i++ )
        {
            ByteArrayOutputStream attachmentFile = attachmentList.get( i );
            byte[] bytes = attachmentFile.toByteArray();
            entry = new ZipEntry( reportFileNames.get( i ) );
            entry.setSize( bytes.length );
            zos.putNextEntry( entry );
            zos.write( bytes );
        }
        messageBodyPart = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource( bout.toByteArray(), "application/zip" );
        messageBodyPart.setDataHandler( new DataHandler( source ) );
        messageBodyPart.setFileName( "Reports.zip" );

    }
    catch( Exception e )
    {
        // TODO: handle exception            
    }
    return messageBodyPart;
}
忘记在每个项目写入后,在for循环结束时调用zos.closeEntry().
如上所述,您还没有关闭ZipOutputStream.

我认为你不需要调用entry.setSize().

否则,这应该工作.

相关文章
相关标签/搜索