Whitebear
Whitebear

Reputation: 1791

Uploading files to a webserver java FileUpload

I'm using apache's FileUpload in order to upload some files to my webserver. Problem is I don't want to upload them to a specific location on the machine i.e : c:\tmp, but rather to a relative path such as /ProjectName/tmp/

Here's my code:

private static final long serialVersionUID = 1L;
private String TMP_DIR_PATH = "c:\\tmp";
private File tmpDir;
private static final String DESTINATION_DIR_PATH ="/files";
private File destinationDir;

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    tmpDir = new File(TMP_DIR_PATH);
    if(!tmpDir.isDirectory()) {
        throw new ServletException(TMP_DIR_PATH + " is not a directory");
    }
    String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
    destinationDir = new File(realPath);
    if(!destinationDir.isDirectory()) {
        throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
    }
}

I want to change TMP_DIR_PATH so it's relative to my project, help would be appreciated!

Upvotes: 1

Views: 1774

Answers (2)

BalusC
BalusC

Reputation: 1109502

If your actual concern is the hardcoding of the c:\\tmp part which makes the code unportable, then consider using File#createTempFile() instead. This will create the file in the platform default temp location as specified by the java.io.tmpdir system property.

File file = File.createTempFile("upload", ".tmp");
OutputStream output = new FileOutputStream(file);
// ...

Upvotes: 3

Femi
Femi

Reputation: 64700

If you want the temp directory to be relative to your project you'll have to use getRealPath and then make sure you create the directory if it doesn't already exist.

You can also use File dir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir"); to fetch an app-specific temp directory provided by the container.

Upvotes: 1

Related Questions