我正在尝试自定义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
?我能做错什么?
感谢。
答案 0 :(得分:0)
看起来MailServiceUtil子系统会旋转一个线程来实际发送电子邮件,而不是等待它返回(因此,线程)。所以在MailServiceUtil.sendEmail()调用之后,我立即删除了要附加的文件,直到实际有机会被发送!
我将查看MailServiceUtil的某种类型的包装器,我可以将文件对象传递给它,然后在实际发送后执行删除。
答案 1 :(得分:0)
您可以尝试使用MailEngine.send方法
发送( InternetAddress,InternetAddress []到,InternetAddress [] cc, InternetAddress [] bcc,InternetAddress [] bulkAddresses, String subject,String body,boolean htmlFormat, InternetAddress [] replyTo,String messageId,String inReplyTo, 文件[]附件)
我不确定MailEngineUtil.sendEmail是否能够正常工作,因为你已经发现它发送到总线然后调用了一个监听器(我认为它的MailMessageListener),即使你没有读取附件你在mailMessage中添加它。