Create folder and upload file using servlet

左心房为你撑大大i 提交于 2019-11-28 10:38:21

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...
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!