当前位置: 代码迷 >> java >> 我保存到磁盘的嵌入式附件已损坏
  详细解决方案

我保存到磁盘的嵌入式附件已损坏

热度:22   发布时间:2023-07-31 12:07:39.0

我有一段代码可以阅读我的收件箱电子邮件。 该代码可识别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);

感谢大家的帮助和提示。 我解决了问题。 这就是我的操作方式:我注意到,在阅读电子邮件正文(假设只有粘贴的图像)时,不仅仅是图像,还有一种HTML,换句话说,正文部分有多部分(在我的情况下为2个部分),所以我必须处理每个部分直到找到图像,这样我才能保存它。 希望这对别人有帮助。 问候。

  相关解决方案