我正在尝试自定义Liferay Web窗体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是否配置正确?我可能做错了什么?

谢谢。

最佳答案

看来MailServiceUtil子系统派生了一个线程来实际发送电子邮件,而不是等待它返回(因此,线程)。因此,在MailServiceUtil.sendEmail()调用之后,我立即删除了要附加的文件,然后才有机会发送该文件!

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

09-26 21:03