2012-03-29 109 views
0

我試圖自定義Liferay Web Form portlet來接受文件上傳,並且除了將文件附加到要發送的電子郵件之外,我幾乎可以完成所有工作。commons-fileupload和Liferay的問題

從表單中獲取字段:

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

看來MailServiceUtil子系統會脫離一個線程來執行電子郵件的實際發送,並且不會等待它返回(因此,線程)。因此,在MailServiceUtil.sendEmail()調用之後,我立即刪除了要附加的文件,然後才真正有機會發送!

我打算查看一下MailServiceUtil的一些封裝類型,我可以將該文件對象傳入,然後一旦其實際發送完成刪除。

0

你可以嘗試使用MailEngine.send方法

發送( 網際地址來自網際地址[]於網際地址[] CC, 網際地址[] BCC,網際地址[] bulkAddresses, 字符串主題,繩體,布爾htmlFormat, 網際地址[]的replyTo,字符串MESSAGEID,字符串inReplyTo, 文件[]附件)

我不知道,如果你理清問題,因爲你已經發現了它發送給MailEngineUtil.sendEmail會甚至工作一輛公共汽車,然後是一個聽衆d被調用(我認爲它的MailMessageListener),即使您將它添加到mailMessage中,它也不會讀取附件。