Java EE - Best way to get real path to uploaded fi

2020-02-10 08:32发布

问题:

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

I'd like to store the files a folder 'files'. And i'd like this folder to be placed 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'm trying to retrieve the files, apparently my bean which tries to access the file does not have access to getServletContext() and thus throws a nullpointer on getRealPath

Now im trying to figure out how i should approach this. I've heard about spring resource is the way to go, but i cant find any relevant examples.

Is there an easy way to get my paths? I just want the rootpath to my webapp. Nothing more nothing less...

回答1:

I'd like this folder to be placed directly under the webapp-root.

This isn't going to work. All those files will get lost whenever you redeploy the webapp or even when you restart the server. Those files are namely not contained as part of the original WAR.

You need to store them in a fixed path outside the webapp's context. E.g. /var/webapp/uploads. You can configure this path in a properties file or as a system property.



回答2:

I've found that a few ways to accomplish this regardless of what OS platform you're using. I typically like to store my files in some way relative to my web application. This being said, the easiest way to do this is using your class file as a reference to get the real path. I use something similar to the following to store image uploads for a few web applications that I've built:

public class FileLocationTest {

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

This can be done using a static utility class in your web app, or any class for that matter to obtain the real path of your application regardless of OS. Alternatively in a servlet I've also used the request class to get the Tomcat location if my appbase is in a different area, something like this:

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