使用servlet创建文件夹和上传文件

时间:2014-05-04 04:05:32

标签: java tomcat servlets apache-commons-fileupload

我有两个使用 tomcat 的web项目..这是我的目录结构..

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

我使用commons-fileupload ..这是我在project1中的 servlet 中的代码

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

这将在'project1'中创建'uploads'文件夹,但我想在'webapps'中创建'uploads'文件夹,因为当我取消部署'project1'时,我不希望'uploads'文件夹消失。

我已经尝试了String root = System.getProperty("catalina.base");但没有工作..

任何人都可以帮助我......提前谢谢

1 个答案:

答案 0 :(得分:2)

首先,在tomcat安装文件夹之外的服务器中创建一个文件夹,例如/opt/myuser/files/upload。然后,在属性文件或web.xml中将此路径配置为Servlet init配置,以使其可用于您拥有的任何Web应用程序。

如果使用属性文件:

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

如果是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>

或者,如果您使用的是Servlet 3.0规范,则可以使用@WebInitParam注释配置init参数:

@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...
    }
}