[英]How to create a ZIP InputStream in Android without creating a ZIP file first?
[英]How to send zip file without creating it on physical location?
我想发送带有zip文件附件的电子邮件。我能够发送pdf文件,而无需使用ByteArrayOutputStream将其保存在实际位置上。 但是,当我尝试将那些文件压缩后,将其发送失败。 它给出异常非法附件。
以下是我编写的用于创建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()。
否则,这应该起作用。
我认为您还没有刷新并关闭ZipOutputStream
。 尝试调用zos.flush(); zos.close()
zos.flush(); zos.close()
。 我希望这将有所帮助。
如果不尝试从ByteArrayOutputStream
提取字节数组,请将其保存到文件中并使用启用zip的工具打开。 仅用于调试,以确保您的ZIP正常且未损坏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.