如何发送zip文件而不在物理位置创建它? [英] How to send zip file without creating it on physical location?
问题描述
我想发送带有zip文件附件的电子邮件..我可以使用ByteArrayOutputStream发送pdf文件,而无需将它们保存在物理位置。但是当我尝试压缩那些文件时,发送它不起作用。它给予例外非法附件。
I want to send email with zip file attachment.. I m able to send pdf files without saving them on physical location using ByteArrayOutputStream. But when I try zip those file an send it its not working. It gives exception illegal attachment.
以下是我为创建zip而编写的代码。
Below is the code which I have written to create 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;
}
推荐答案
你忘了打电话给zos。写入每个项目后的closeEntry(),在for循环结束时。
如上所述,您尚未关闭ZipOutputStream。
You forgot to call zos.closeEntry() after each item is written, at the end of your for loop. And as noted, you haven't closed your ZipOutputStream.
我认为您不需要调用entry.setSize()。
I don't think you need to call entry.setSize(), either.
否则,这应该有效。
这篇关于如何发送zip文件而不在物理位置创建它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!