2

When uploading 1-6969875-2644-t.jpg, the image is uploaded to /home/xrcwrn/jvm/apache-tomcat-6.0.14/domains/xyz.com/ROOT/img/1-6969875-2644-t.jpg properly.

But I actually want to upload this image into the /home/xrcwrn/public_html/img folder.

I am using this code in 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;
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
xrcwrn
  • 5,339
  • 17
  • 68
  • 129

1 Answers1

4

Don't use ServletContext#getRealPath(). You don't want to write uploaded files to there. They will get lost whenever you redeploy the webapp or even when you restart the server.

Replace

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

by

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

If you want to make this configureable, consider providing it as a system property or a properties file setting.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555