[英]How to send zip file without creating it on physical location?
I want to send email with zip file attachment.. I m able to send pdf files without saving them on physical location using ByteArrayOutputStream. 我想发送带有zip文件附件的电子邮件。我能够发送pdf文件,而无需使用ByteArrayOutputStream将其保存在实际位置上。 But when I try zip those file an send it its not working.
但是,当我尝试将那些文件压缩后,将其发送失败。 It gives exception illegal attachment.
它给出异常非法附件。
Below is the code which I have written to create zip. 以下是我编写的用于创建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;
}
You forgot to call zos.closeEntry() after each item is written, at the end of your for loop. 在for循环结束时,您在写入每个项目之后忘记调用zos.closeEntry()。 And as noted, you haven't closed your ZipOutputStream.
如前所述,您尚未关闭ZipOutputStream。
I don't think you need to call entry.setSize(), either. 我也不认为您需要调用entry.setSize()。
Otherwise, this should work. 否则,这应该起作用。
I think that you have not flushed and closed ZipOutputStream
. 我认为您还没有刷新并关闭
ZipOutputStream
。 Try to call zos.flush(); zos.close()
尝试调用
zos.flush(); zos.close()
zos.flush(); zos.close()
. zos.flush(); zos.close()
。 I hope this will help. 我希望这将有所帮助。
If not try to extract byte array from your ByteArrayOutputStream
, save it into file and open with zip-enable tool. 如果不尝试从
ByteArrayOutputStream
提取字节数组,请将其保存到文件中并使用启用zip的工具打开。 It is just for debugging to be sure that your ZIP is OK and is not corrupted. 仅用于调试,以确保您的ZIP正常且未损坏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.