2012-12-18 46 views
0

我通過struts2文件上傳攔截器上傳用戶個人資料圖片。上傳圖片後,我想將其保存在webapp/upload/images文件夾下的webapp中。我用下面的代碼來做到這一點。文件上傳後Struts2文件複製到不同的文件夾?

public String uploadPhoto() { 
    try { 
     String filePath = servletRequest.getContextPath() + "/uploads/images"; 
     System.out.println("Server path:" + filePath); 
     File fileToCreate = new File(filePath, this.userImageFileName); 

     FileUtils.copyFile(this.userImage, fileToCreate); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     addActionError(e.getMessage()); 

     return INPUT; 
    } 
    return SUCCESS; 
} 

但我得到以下錯誤

Server path:/picvik/uploads/images 
java.io.IOException: Destination '/picvik/uploads/images/one.jpg' directory cannot be created 
    at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:777) 
    at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:731) 
    at com.picvik.action.ChangePhotoAction.uploadPhoto(ChangePhotoAction.java:28) 

請更正一下,我做錯了。以及如何實現這一點。我基本上想要將所有用戶個人資料圖片保存在我的webapp下:webapp/uploads/images。

回答

1

這是非常簡單的,你可以不使用相對路徑創建一個文件,你應該使用它的真實路徑:

String filePath = servletRequest.getContextPath().getRealPath("/uploads/images"); 

它應該是那麼好。

+3

出於各種原因,您幾乎肯定不應將圖像保存到Web應用程序中的目錄。 –

相關問題