2011-08-16 25 views
2

上傳1-6969875-2644-t.jpg時,圖片正確上傳至 /home/xrcwrn/jvm/apache-tomcat-6.0.14/domains/xyz.com/ROOT/img/1-6969875-2644-t.jpg如何將struts 2中的照片上傳到我的public_html目錄而不是我的tomcat目錄中?

但我其實想把這個圖像上傳到/home/xrcwrn/public_html/img文件夾中。

我使用這段代碼的Struts 2:

public String execute() { 

    try { 
     ServletContext servletContext = ServletActionContext.getServletContext(); 
     String path =servletContext.getRealPath("/img"); 
     System.out.println("Server path:" + path); 
     String filePath = servletContext.getRealPath(path); 
     File uploadDir = new File(filePath); 
     String relPath = uploadDir.getAbsolutePath(); 
     //if the folder does not exits, creating it 
     if (uploadDir.exists() == false) { 
      uploadDir.mkdirs(); 
     } 
     File fileToCreate = new File(path, this.userImageFileName); 
     FileUtils.copyFile(this.userImage, fileToCreate); 
     String pt = path + "/" + getUserImageFileName(); 
     System.out.println("image path is :" + pt); 
     setImagePath(pt); 
     } catch (Exception e) { 

     e.printStackTrace(); 
     addActionError(e.getMessage()); 
     return INPUT; 
    } 
    System.out.println(" **************inside image upload***********"); 

    return SUCCESS; 
} 

回答

4

不要使用ServletContext#getRealPath()。你不想寫上傳的文件到那裏。重新部署Web應用程序或重新啓動服務器時,它們都會丟失。

通過

String filePath = "/home/xrcwrn/public_html/img"; 

如果你想使這個configureable,考慮提供它作爲一個系統屬性或屬性文件中設置替換

String path =servletContext.getRealPath("/img"); 
System.out.println("Server path:" + path); 
String filePath = servletContext.getRealPath(path); 

相關問題