0

我正在尝试自定义 Liferay Web Form portlet 以接受文件上传,除了将文件附加到要发送的电子邮件之外,我已经完成了几乎所有工作。

从表单中获取字段:

public void saveData(ActionRequest actionRequest, ActionResponse actionResponse) {

...

File uploadedFile = null;

...

Map<String,String> fieldsMap = new LinkedHashMap<String,String>();

// Create a FileItemFactory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory(1073741824, new File("/temp"));

// Create a new file upload handler
PortletFileUpload upload = new PortletFileUpload(factory);
upload.setSizeMax(67108864);

// Parse the request
List<FileItem> items = upload.parseRequest(actionRequest); 

int i = 1;

Iterator iter = items.iterator();

// Throw away the hidden field, don't need it
FileItem dud = (FileItem)iter.next();

while (iter.hasNext()) {

    FileItem item = (FileItem)iter.next();

    String fieldLabel = preferences.getValue(
        "fieldLabel" + i, StringPool.BLANK);

    String fieldType = preferences.getValue(
            "fieldType" + i, StringPool.BLANK);

    if (Validator.isNull(fieldLabel)) {
        break;
    }

    if(!fieldType.equals("file")) {
        String fieldValue = item.getString();
        fieldsMap.put(fieldLabel, fieldValue);
    } else {
        String fieldName = item.getName();
        uploadedFile = new File(fieldName);
        item.write(uploadedFile);
    }
        i++;
}
...

     if(sendAsEmail) {
         emailSuccess = sendEmail(fieldsMap, preferences, uploadedFile);
     }
}

然后是邮件的构建和发送:

protected boolean sendEmail(Map<String, String> fieldsMap, PortletPreferences preferences, File uploadedFile) {

    MailMessage mailMessage = new MailMessage(fromAddress, toAddress, subject, body, false);

    if(uploadedFile != null) { // i.e., there was 'file' field up above
        mailMessage.addAttachment(uploadedFile);
    }

    MailServiceUtil.sendEmail(mailMessage);


    if(uploadedFile != null) {
       uploadedFile.delete();
    }

}

尝试处理文件上传并将文件附加到消息时出现以下控制台错误:

16:09:49,597 ERROR [MailEngine:489] IOException while sending message
16:09:49,598 ERROR [MailEngine:154] java.io.FileNotFoundException: helpdesk_.png (No such file or directory)

我的DiskFileItemFactory配置是否正确?我可能做错了什么?

谢谢。

4

2 回答 2

1

MailServiceUtil 子系统似乎从一个线程中分离出一个线程来执行电子邮件的实际发送,并且不等待它返回(因此,线程)。因此,在 MailServiceUtil.sendEmail() 调用之后,我立即删除了要附加的文件,然后才真正有机会发送!

我将研究 MailServiceUtil 的某种类型的包装器,我可以将文件对象传递到其中,然后在实际发送后执行删除。

于 2012-03-29T19:37:15.867 回答
0

您可以尝试使用 MailEngine.send 方法吗

发送(InternetAddress from,InternetAddress[] to,InternetAddress[] cc,InternetAddress[] bcc,InternetAddress[] bulkAddresses,字符串主题,字符串正文,布尔 htmlFormat,InternetAddress[] 回复,字符串 messageId,字符串 inReplyTo,文件 [] 附件)

我不确定 MailEngineUtil.sendEmail 是否会工作,即使你已经解决了问题,因为你已经发现它发送到总线然后会调用一个监听器(我认为它的 MailMessageListener)即使你添加它也不会读取附件在邮件消息中。

于 2012-03-30T09:09:23.840 回答