开发者

Uploading files to a webserver java FileUpload

开发者 https://www.devze.com 2023-03-24 16:56 出处:网络
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 pat

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.isDire开发者_运维百科ctory()) {
        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!


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);
// ...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消