Java Servlets | Converting relative path to absolute for file upload

|
| By Webner

In the program of uploading files to a server location, instead of using absolute location for saving file to that path, relative path needs to be used. Program was working correctly for absolute path.

In the maven project with the following directory structure , I created a resources folder in the webapp, and I needed to upload files in the folder named “uploaded_docs” created in the resources folder but just giving relative path for that folder was not working example:

/resources/uploaded_docs:

1
While the relative path worked simply for image “src” attribute in the jsp page by just giving “images” folder relative location as “/resources/images”:

<img src=”resources/images/images.jpeg”  style=”width:304px;height:228px;”>

While uploading files the relative location dosen’t work. This problem is solved by converting the relative path to real path location. This is done by obtaining the location of current working directory programmatically.
In the following controller action, String rpath is the relative path of location where files are to be uploaded and appPath is the location of current working directory which is calculated by using the function of context.getRealPath(“”); of ServletContext class.
String path variable gives the complete location i.e the real path where file is to be uploaded:

public ModelAndView UploadFiles(@ModelAttribute("uploadForm") UploadClass uploadForm, HttpServletRequest request) throws IOException, SQLException {
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    String rpath = "/resources/uploaded_docs";

    path = appPath + rpath;

    System.out.println("Current Working Directory:" + appPath);
    System.out.println("\n\n");
    System.out.println("Relative File path for uploading files:" + rpath);
    System.out.println("\n\n");
    System.out.println("Current file Upload location:" + path);
    System.out.println("\n\n");…………..…………………………..……………………………………..
    //file upload code	 
    ……………………………….…………………………………….
}

Poject compiled under war file named ‘zac’ produces the following console output for path.
//Output:
2

Leave a Reply

Your email address will not be published. Required fields are marked *