Create folder and upload file using servlet

后端 未结 1 1863
闹比i
闹比i 2020-12-10 10:01

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

webapps
--project1
  --WEB-INF
--project2
  --WEB-INF
1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 10:35

    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:

    
        MyServlet
        your.package.MyServlet
        
            FILE_UPLOAD_PATH
            /opt/myuser/files/upload
        
    
    

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

    0 讨论(0)
提交回复
热议问题