小编典典

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

tomcat

我有两个使用 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");但是没有用..

谁能帮我…提前感谢


阅读 581

收藏
2020-06-16

共1个答案

小编典典

首先,在服务器中的tomcat安装文件夹之外创建一个文件夹,例如/opt/myuser/files/upload。然后,在属性文件或web.xml中将此路径配置为Servlet初始化配置,以使其可用于您拥有的任何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...
    }
}
2020-06-16