如何将电子邮件附件直接保存到数据库而不保存到HDD First?

问题描述 投票:0回答:1

我找到了一个很好的Java脚本,它连接到我的电子邮件服务器并从中获取新的电子邮件内容。这个java程序,也将电子邮件附件下载到我的硬盘上。但我需要将附件(PDF,EXCEL,WORD,IMAGES等)直接保存到我的数据库,而不是先保存到HDD然后上传到我的数据库(我正在使用Oracle 12C数据库)表。

我是Java菜鸟程序员,欢迎提出我的问题的任何提示。谢谢!

以下是将附件保存到HDD的剪辑代码:

public void procesMultiPart(Multipart content) {

    try {

        for (int i = 0; i < content.getCount(); i++) {
            BodyPart bodyPart = content.getBodyPart(i);
            Object o;

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

            } else if (null != bodyPart.getDisposition() && bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {

                String fileName = bodyPart.getFileName();

                System.out.println("fileName = " + fileName);
                InputStream inStream = bodyPart.getInputStream();
                FileOutputStream outStream = new FileOutputStream(new File(downloadDirectory + fileName));
                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();
    }

}
java database email-attachments
1个回答
0
投票

警告:我无法真正测试这个,但这基本上就是你要找的东西:

    //----------snip
                InputStream inStream = bodyPart.getInputStream();
                //The outstream can be any output stream, I switch this to one that writes to memory (byte[]).      
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                byte[] tempBuffer = new byte[4096]; // 4 KB
                int numRead;
                while ((numRead = inStream.read(tempBuffer)) != -1) {
                    outStream.write(tempBuffer);
                }

                //Handle object here
                byte[] attachment = outStream.toByteArray(); 

                //Pseudo Code Begins
                SQL.createAttachment(attachment); //I'm assuming there's a static method to do this
                inStream.close();
                outStream.close();
//-----------------snip

代码实际上是相同的,您只需要正确地定位数据。这意味着连接到您的数据库,编写一些SQL(或使用框架)插入其中等...

这可能超出了单个问题答案的范围。我该怎么处理?可能是这样的(我假设你可以打开一个连接,并让所有工作。我显然没有架构)。

static Connection oracle; //Psuedo Code
//SQL class
public static createAttachment(byte[] blob)
{ 
  //exception handling skipped 
  Query q = oracle.createQuery("INSERT INTO Attachments Values(?)");
  q.setParameter(0, blob);
  q.execute();  
}

我希望能指出你正确的方向。它不全面,但它是一个解决方案。这也是一个糟糕的设计,但它可能不是你正在使用的问题。我甚至没有解决这方面的资源管理问题。

© www.soinside.com 2019 - 2024. All rights reserved.