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

DMS*_*DMS 9 java java-ee

我想发送带有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;
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*exR 0

我认为你还没有冲水并关闭ZipOutputStream。尝试打电话zos.flush(); zos.close()。我希望这个能帮上忙。

如果没有尝试从您的 中提取字节数组ByteArrayOutputStream,请将其保存到文件中并使用 zip 启用工具打开。它只是为了调试以确保您的 ZIP 正常并且没有损坏。