我保存到磁盘的内联附件已损坏

The inline attachment i save to disk is corrupted

我有一段代码可以读取我的收件箱电子邮件。该代码识别 2 种附件:

1) 附件,下载后保存到数据库。这很好用。

2) 内联附件(我在测试中使用图像作为附件)。代码检测到这种附件,但当我将它们保存到磁盘时,文件似乎已损坏。我检查了生成的文件属性,发现它没有基本信息(像素、高度、宽度)。我认为文件在下载到磁盘时没有正确保存(我试过 PNG 和 JPG)。我认为该文件需要用一种 mimetype 属性保存,这样我才能正确打开它。请问有什么建议吗?提前致谢!

这是我的代码片段:

public void procesMultiPart(Multipart content) throws SQLException {

    try {

        for (int i = 0; i < content.getCount(); i++) {
            BodyPart bodyPart = content.getBodyPart(i);
            Object o;
            String downloadDirectory = "D:/Attachment/";

            o = bodyPart.getContent();
            if (o instanceof String) {
                System.out.println("procesMultiPart es plainText");

            } else if (null != bodyPart.getDisposition() && bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
                    System.out.println("IS ATTACHMENT...");
                    // i save the attachment to database and is OK..
            } else if (bodyPart.getDisposition() == null){
                System.out.println("IS AN INLINE ATTACHMENT...");
                String fileNameinline = "inline" + i + ".png";
                InputStream inStream = bodyPart.getInputStream();
                FileOutputStream outStream = new FileOutputStream(new File(downloadDirectory + fileNameinline), true);
                byte[] tempBuffer = new byte[4096];// 4 KB
                int numRead;
                while ((numRead = inStream.read(tempBuffer)) != -1) {
                    outStream.write(tempBuffer);
                }
                inStream.close();
                outStream.close();                  
            }

        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }

}

文件已损坏,因为您将其写入光盘的方式不正确:

outStream.write(tempBuffer);

您只应写入与读取的字节数相同的字节数:

outStream.write(tempBuffer, 0, numRead);

感谢大家的帮助和提示。我解决了这个问题。我是这样做的:我注意到在阅读电子邮件 body 时(假设只有粘贴的图像),除了图像之外还有更多内容,还有一种 HTML,所以换句话说,body 部分有多个部分(在我的例子中是 2 个部分),所以我必须处理每个部分直到找到图像,这样我才能保存它。 希望这对别人有帮助。 问候