Java EE - best way to get real path to uploaded files?

I have a web application with a upload form where users can upload files.

I would like to save the files in the “files” folder. And I would like this folder to be located directly under the webapp root.

Using struts2, in my uploadFileAction, I can easily set this path with String uploadDir = ServletActionContext.getServletContext().getRealPath("/files")+ "/";

But when I try to get the files, apparently my bean, which is trying to access the file, has no access to, getServletContext()and thus throws a null pointer togetRealPath

Now I'm trying to figure out how I should approach this. I heard about the spring resource, this is the way, but I can not find the relevant examples.

Is there an easy way to get my ways? I just want the rootpath for my webapp. Nothing less than that ...

+5
source share
2 answers

I would like this folder to be located directly under the webapp root.

This will not work. All of these files will be lost every time you redeploy webapp or even when the server restarts. These files are not contained as part of the original WAR.

You need to save them in a fixed path outside the webapp context. For instance. /var/webapp/uploads. You can configure this path in the properties file or as a system property.

+8
source

, . - -. - . - -, :

public class FileLocationTest {

    public static void main(String[] args) {
        String path = FileLocationTest.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        System.out.println(path);
    }
}

, - , . , , Tomcat, , :

    String location = request.getClass().getProtectionDomain().getClassLoader().getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
    String path = location.substring(0, location.indexOf("/tomcat")) + "/data/events/images/";
+3

All Articles