Create folder and upload file using servlet

nat picture nat · May 4, 2014 · Viewed 7.9k times · Source

I have two web project that use tomcat..this is my directory structure..

webapps
--project1
  --WEB-INF
--project2
  --WEB-INF

I use commons-fileupload..this is part my code in servlet in project1

String fileName = item.getName();    
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");

if (!path.exists()) {
    path.mkdirs();
}

File uploadedFile = new File(path + File.separator + fileName);
item.write(uploadedFile);

This will create 'uploads' folder in 'project1' but I want to create 'uploads' folder in 'webapps' because I dont want 'uploads' folder gone when I undeploy 'project1'..

I already try String root = System.getProperty("catalina.base"); but not work..

Can anyone help me...thanks in advance

Answer

Luiggi Mendoza picture Luiggi Mendoza · May 4, 2014

First, create a folder in your server outside the tomcat installation folder, for example /opt/myuser/files/upload. Then, configure this path in a properties file or in web.xml as a Servlet init configuration to make it available for any web application you have.

If using properties file:

file.upload.path = /opt/myuser/files/upload

If web.xml:

<servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>your.package.MyServlet</servlet-class>
    <init-param>
        <param-name>FILE_UPLOAD_PATH</param-name>
        <param-value>/opt/myuser/files/upload</param-value>
    </init-param>
</servlet>

Or if you're using Servlet 3.0 specification, you can configure the init params using @WebInitParam annotation:

@WebServlet(name="MyServlet", urlPatterns = {"/MyServlet"},
    initParams = {
        @WebInitParam(name = "FILE_UPLOAD_PATH", value = "/opt/myuser/files/upload")
    })
public class MyServlet extends HttpServlet {
    private String fileUploadPath;
    public void init(ServletConfig config) {
        fileUploadPath = config.getInitParameter("FILE_UPLOAD_PATH");
    }
    //use fileUploadPath accordingly

    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException) {
        String fileName = ...; //retrieve it as you're doing it now
        //using File(String parent, String name) constructor
        //leave the JDK resolve the paths for you
        File uploadedFile = new File(fileUploadPath, fileName);
        //complete your work here...
    }
}