Version 5

    Chinse version:

    https://community.jboss.org/wiki/JbossWeb-JSFServlet-ChinseVersion

    or
    http://javaarm.com/faces/display.xhtml?tid=3109

     

     

     

     

    upload with JSF and servlet

     

    Environment: JBoss AS 7.2.0.

     

    During the development of my personal web site (http://javaarm.com), I met upload problems and solved them, so I summarize and post them here. I hope it is useful to other guys.

     

    Reference:http://docs.oracle.com/javaee/6/tutorial/doc/glrbb.html

    Chapter 16 Uploading Files with Java Servlet Technology

    #

    Supporting file uploads is a very basic and common requirement for many web applications. Prior to Servlet 3.0, implementing file upload required the use of external libraries or complex input processing. Version 3.0 of the Java Servlet specification helps to provide a viable solution to the problem in a generic and portable way. The Servlet 3.0 specification supports file upload out of the box, so any web container that implements the specification can parse multipart requests and make mime attachments available through the HttpServletRequest object.

    A new annotation, javax.servlet.annotation.MultipartConfig, is used to indicate that the servlet on which it is declared expects requests to made using the multipart/form-data MIME type. Servlets that are annotated with @MultipartConfig can retrieve the Part components of a given multipart/form-data request by calling the request.getPart(String name) or request.getParts() method.

    The following topics are addressed here:

     

    Notice on html <form /> element

    (1) We must set the value of 'method' attribute to "post" and set the value of 'enctype' attribute to "multipart/form-data". For example:<form method="post" action="UploadServlet" enctype="multipart/form-data" >

     

    (2) About the 'action' attribue:

    Suppose:

         (a) Our web application in jboss deployment directory is: ${JBOSS_HOME}\standalone\deployments\ybxiang-forum.ear\ybxiang-forum-war.war

         (b) Upload page is ${JBOSS_HOME}\standalone\deployments\ybxiang-forum.ear\ybxiang-forum-war.war/upload/upload.jsp

     

    Then

    • If upload.jsp's form is <form method="post" action="UploadServlet" enctype="multipart/form-data" >, then action="UploadServlet" will be parsed by web browser as action="http://domain-name/upload/UploadServlet" instead of action="http://domain-name/UploadServlet". In this case, your UploadServlet.java should be mapped to /upload/UploadServlet. For example, we can do it by adding an annotation: @WebServlet("/upload/UploadServlet"). (NOT RECOMMENDATED.)
    • If upload.jsp's form is <form method="post" action="/UploadServlet" enctype="multipart/form-data" >, then action="/UploadServlet" will be parsed by web browser as action="http://domain-name/UploadServlet" instead of action="http://domain-name/upload/UploadServlet". In this case, your UploadServlet.java should be mapped to "/UploadServlet". For example, we can do it by adding an annotation: @WebServlet("/UploadServlet"). (RECOMMENDATED.)

     

    **********************************************************************************************************************************************************

     

    1. HTML/JSF/JSP page + <form /> + Upload Servlet

     

    In html/JSF/JSP pages, it is possible to upload with standard html <form />

     

     

     

    1.1 HTML/JSF/JSP pages example

     

    <form method="post" action="/UploadServlet" enctype="multipart/form-data" >
        Directory:  <input type="text" name="targetDirectory" value="/home/ybxiang/file/" size="60" /><br />
        File:<input type="file" name="file1" id="file1" /> <br/>
        File:<input type="file" name="file2" id="file2" /> <br/>
        <input type="submit" value="Upload" name="upload" id="upload" />
    </form>

     

     

     

    1.2 UploadServlet.java

    We just list the skeleton of this class here and will describe it in detail in last section.

     

    @WebServlet("/UploadServlet")

    public class UploadServlet_CalledByJSF extends HttpServlet {

        private static final long serialVersionUID = 1L;

        protected void doPost(HttpServletRequest request,

                HttpServletResponse response) throws ServletException, IOException {

            response.setContentType("text/html;charset=UTF-8");

            ...

        }

    }

    ...

     

    2. JSF page + <h:form /> + Upload Servlet

     

    JSF element <h:form /> has NO method and action attributes:

    (a) its 'method' is always 'post'

    (b) its action is generated by <h:commandButton /> in the <h:form />

     

    So,  you should NOT tell <h:form /> to call certain Upload Servlet.

     

     

    Bellow example is WRONG:

     

    2.1 JSF

    <h:form method="post" action="/UploadServlet" enctype="multipart/form-data">

        File:

        <input type="file" name="file" id="file" /> <br/>

        Destination:

        <input type="text" value="/tmp" name="destination"/>

        <br />

        <input type="submit" value="Upload" name="upload" id="upload" />

    </h:form>

     

     

    this form will be parsed by web browser as:

    <form id="j_idt122" name="j_idt122" method="post" action="/faces/system/upload-bad.xhtml" enctype="multipart/form-data">

    <input name="j_idt122" value="j_idt122" type="hidden">

     

     

    You can see that the action is not pointed to "/UploadServlet"!

     

     

     

    3. JSF page  + <h:inputFile /> +JSF MBean (NOT tested!)

     

    JSF 2.2 support new <h:inputFile /> tag, so we can upload files with JSF MBeans directly.

     

     

    3.1 JSF page

    <h:form enctype="multipart/form-data">

        <h:inputFile id="file"  value="#{fileUploadMBean.file1}"/><br />

        <h:commandButton id="button" action="#{fileUploadMBean.upload()}" value="Upload"/>

    </h:form>

     

    3.2 JSF MBean - FileUploadMBean.java

     

    import javax.faces.bean.ManagedBean;

    import javax.faces.bean.RequestScoped;

    import javax.servlet.http.Part;

     

    import com.ybxiang.forum.jsfmbean.Constants;

    import com.ybxiang.forum.jsfmbean.JSFHelper;

     

    /**

    * http://javaarm.com/faces/display.xhtml?tid=3109

    * (a) http://docs.oracle.com/javaee/6/tutorial/doc/glrbb.html

    * (b) http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html

    */

    @ManagedBean

    @RequestScoped

    public class FileUploadMBean {

        private Part file1;

        private Part file2;

        private Part file3;

        private Part file4;

        private Part file5;

       

        public Part getFile1() {

            return file1;

        }

        public void setFile1(Part file1) {

            this.file1 = file1;

        }

     

        public Part getFile2() {

            return file2;

        }

        public void setFile2(Part file2) {

            this.file2 = file2;

        }

     

        public Part getFile3() {

            return file3;

        }

        public void setFile3(Part file3) {

            this.file3 = file3;

        }

     

        public Part getFile4() {

            return file4;

        }

        public void setFile4(Part file4) {

            this.file4 = file4;

        }

     

        public Part getFile5() {

            return file5;

        }

        public void setFile5(Part file5) {

            this.file5 = file5;

        }

     

        public String upload(){

            boolean jsf22Supported = false;

            if(! jsf22Supported){

                String errMsg = "当前JBoss AS不支持JSF2.2(JSF从2.2版本才开始支持 <h:inputFile />)!";

                JSFHelper.addErrorMessage(errMsg);

                return Constants.RETURN_FAILURE;

            }

            //TODO:permission limitation.

            //TODO: file size limitation

            //TODO: image width limitation.

           

            String file1_name = getFileName(getFile1());

            String file2_name = getFileName(getFile2());

            String file3_name = getFileName(getFile3());

            String file4_name = getFileName(getFile4());

            String file5_name = getFileName(getFile5());

            try{

                getFile1().write("d://upload"+file1_name);

                getFile2().write("d://upload"+file2_name);

                getFile3().write("d://upload"+file3_name);

                getFile4().write("d://upload"+file4_name);

                getFile5().write("d://upload"+file5_name);

            }catch(Exception e){

                String errMsg = e.getMessage();

                JSFHelper.addErrorMessage(errMsg);

                return Constants.RETURN_FAILURE;

            }

     

            return Constants.RETURN_SUCCESS;

        }

       

        private String getFileName(final Part part) {

            for (String content : part.getHeader("content-disposition").split(";")) {

                if (content.trim().startsWith("filename")) {

                    return content.substring(content.indexOf('=') + 1).trim()

                            .replace("\"", "");

                }

            }

            return null;

        }

    }

     

     

     

    5. UploadServlet.java in details

     

    About javax.servlet.annotation.MultipartConfig

    @java.lang.annotation.Target(value={java.lang.annotation.ElementType.TYPE})
    @java.lang.annotation.Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME)
    public abstract @interface javax.servlet.annotation.MultipartConfig extends java.lang.annotation.Annotation {
      public abstract java.lang.String location() default "";
      public abstract long maxFileSize() default -1L;
      public abstract long maxRequestSize() default -1L;
      public abstract int fileSizeThreshold() default (int) 0;
    }

    Reference 1:http://docs.oracle.com/javaee/6/tutorial/doc/glrbb.html

    *************************************************************************************************

    A new annotation, javax.servlet.annotation.MultipartConfig, is used to indicate that the servlet on which it is declared expects requests to made using the multipart/form-data MIME type. Servlets that are annotated with @MultipartConfig can retrieve the Part components of a given multipart/form-data request by calling the request.getPart(String name) or request.getParts() method.

    *************************************************************************************************

     

    Reference 2:http://docs.oracle.com/javaee/6/tutorial/doc/gmhal.html

    *************************************************************************************************

    The @MultipartConfig Annotation

    The @MultipartConfig annotation supports the following optional attributes:

    • location: An absolute path to a directory on the file system. The location attribute does not support a path relative to the application context. This location is used to store files temporarily while the parts are processed or when the size of the file exceeds the specified fileSizeThreshold setting. The default location is "".
    • fileSizeThreshold: The file size in bytes after which the file will be temporarily stored on disk. The default size is 0 bytes.
    • MaxFileSize: The maximum size allowed for uploaded files, in bytes. If the size of any uploaded file is greater than this size, the web container will throw an exception (IllegalStateException). The default size is unlimited.
    • maxRequestSize: The maximum size allowed for a multipart/form-data request, in bytes. The web container will throw an exception if the overall size of all uploaded files exceeds this threshold. The default size is unlimited.

    For, example, the @MultipartConfig annotation could be constructed as follows:

    @MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024, maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)

    Instead of using the @MultipartConfig annotation to hard-code these attributes in your file upload servlet, you could add the following as a child element of the servlet configuration element in the web.xml file.

    <multipart-config> <location>/tmp</location> <max-file-size>20848820</max-file-size> <max-request-size>418018841</max-request-size> <file-size-threshold>1048576</file-size-threshold> </multipart-config>

    *************************************************************************************************

     

     

     

    5.1 UploadServlet.java without @MultipartConfig (recommended)

     

    If the UploadServlet.java is NOT annotated with @MultipartConfig(...), then Servlet container will NOT extract parameters from javax.servlet.http.Part and put them into request.getParameterMap(), so request.getParameterMap() contians nothing!!!

     

    But, we can  use Apache commons-fileupload-1.2.2.jar and commons-io-2.3.jar to extract files and parameters from javax.servlet.http.Part.

     

    (a) UploadServlet_WithoutMultipartConfig.java

     

    import java.io.File;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Iterator;
    import java.util.List;

     

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

     

    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;

     

    /**
    * 参考: http://javaarm.com/faces/display.xhtml?tid=2190
    */
    @WebServlet("/UploadServlet")
    public class UploadServlet_WithoutMultipartConfig extends HttpServlet {
        private static final long serialVersionUID = 1L;
       
        public static final int DEFAULT_UPLOAD_maxFileSize = 5242880;
        public static final int DEFAULT_UPLOAD_maxRequestSize = 418018841;
        public static final int DEFAULT_UPLOAD_fileSizeThreshold = 1048576;
       
        public static final String FILED_NAME_targetDirectory = "targetDirectory";
       
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
           
            String targetDirectory = request.getParameter(FILED_NAME_targetDirectory);
            if(targetDirectory==null){
                System.out.println("This is normal:");
                System.out.println("If we do NOT declare @MultipartConfig() on UploadServlet, ");
                System.out.println("all fileds(<input type='text' ... />, <input type='file' .. />) in html from is wrapped in javax.servlet.http.Part, ");
                System.out.println("so, request.getParameterMap() contains nothing!");
            }else{
                System.out.println("IMPOSSIBLE!");
            }
                   
            if (!ServletFileUpload.isMultipartContent(request)) {
                printFeedBackInfo(response,"Request中没有上传文件!请确保<form>的enctyp为'multipart/form-data'!");
                return;
            }
           
            //File targetDirectoryFile = new File(targetDirectory);
            //if(! targetDirectoryFile.exists()){
            //    targetDirectoryFile.mkdirs();
            //}

            DiskFileItemFactory factory = new DiskFileItemFactory();

            factory.setSizeThreshold(DEFAULT_UPLOAD_fileSizeThreshold);

            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

           

            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setFileSizeMax(DEFAULT_UPLOAD_maxFileSize);

            upload.setSizeMax(DEFAULT_UPLOAD_maxRequestSize);

           

            StringBuilder sb_success = new StringBuilder("上传成功的文件:<br/>");

            StringBuilder sb_failure = new StringBuilder("上传失败的文件:<br/>");

            try {

                @SuppressWarnings("unchecked")

                List<FileItem> list = (List<FileItem>)upload.parseRequest(request);

               

                targetDirectory = getParameter(list, FILED_NAME_targetDirectory);

                if(targetDirectory==null){

                    printFeedBackInfo(response,"IMPOSSIBLE: targetDirectory is null.");

                    return;

                }

                File targetDirectoryFile = new File(targetDirectory);

                if(! targetDirectoryFile.exists()){

                    targetDirectoryFile.mkdirs();

                }

               

                Iterator<FileItem> it = list.iterator();

                while (it.hasNext()) {

                    FileItem item = it.next();

                    if (!item.isFormField()) {

                        String fileName = new File(item.getName()).getName();

                        if(fileName==null||fileName.trim().length()==0){

                            //<input type="file" name="file_i" size="60" /> is NOT selected.

                        }else{

                            item.write(new File(targetDirectory,fileName));

                            sb_success.append(fileName).append("<br />");

                        }

                    }

                }

            } catch (Exception ex) {

                printFeedBackInfo(response,"错误:"+ex.getMessage());

                return;

            }

     

            StringBuilder sb_result = new StringBuilder("上传结果:<br />");

            sb_result.append("(a) ").append(sb_success.toString()).append("<br/>");

            sb_result.append("(b) ").append(sb_failure.toString());

            printFeedBackInfo(response,sb_result.toString());

        }

     

     

        private String getParameter(List<FileItem>list,String parameterName){

            Iterator<FileItem> it = list.iterator();

            while (it.hasNext()) {

                FileItem item = it.next();

                if (!item.isFormField()) {

                    //Ignore File Item!

                }else{

                    if(item.getFieldName().equals(parameterName)){

                        return item.getString();

                    }

                }

            }

            return null;

        }

     

     

        private void printFeedBackInfo(HttpServletResponse response,String info) throws IOException{

            PrintWriter writer = response.getWriter();

            writer.println(info);

            writer.flush();

        }

    }

     

     

    (b) html form

    <form method="post" action="/UploadServlet" enctype="multipart/form-data" >

        Directory:  <input type="text" name="targetDirectory" value="/home/ybxiang/file/" size="60" /><br />

        File:<input type="file" name="file1" id="file1" /> <br/>

        File:<input type="file" name="file2" id="file2" /> <br/>

        <input type="submit" value="Upload" name="upload" id="upload" />

    </form>

     

     

     

     

     

    5.2 UploadServlet.java - with @MultipartConfig

    如果我们为 UploadServlet.java 声明注解@MultipartConfig(...),那么html form中的所有fields(包括<input type='text' ... />, <input type='file' .. />...)都将被封装进 javax.servlet.http.Part;而Servlet容器会把参数信息从 javax.servlet.http.Part里面解析出来,放入UploadServlet的HttpServletRequest中;这样 request.getParameterMap()就包含了我们期望的参数的信息!

     

    在这个情况下,Apache的 commons-fileupload-1.2.2.jar和commons-io-2.3.jar从request中读取这些 javax.servlet.http.Part 就会有问题:为空!我们可以直接从 javax.servlet.http.Part里面读取文件,参见:http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html

     

    bellow useages of @MultipartConfig are equivalent:

    • No parameters
    @MultipartConfig
    • Default parameters:
    @MultipartConfig(
            location="",
            fileSizeThreshold = 0,
            maxFileSize = -1,
            maxRequestSize = -1)
    • Max parameters
    @MultipartConfig(
            location="",
            fileSizeThreshold = Integer.MAX_VALUE,
            maxFileSize = Long.MAX_VALUE,
            maxRequestSize = Long.MAX_VALUE)

    NOTE:

    • If maxFileSize is set to 2M and uploaded file is 5M, then all fields (including <input type='text' ... />, <input type='file' .. />) in HttpServletRequest will be ignored! We can get nothing.
    • If maxRequestSize is set to 10M and total uploaed files and parameters fileds are over 10M, then all fields (including <input type='text' ... />, <input type='file' .. />) in HttpServletRequest will be ignored! We can get nothing.

     

     

     

    5.2.1 extract files with commons-fileupload-1.2.2.jar and commons-io-2.3.jar (failed and not recommended)

    import java.io.File;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Iterator;
    import java.util.List;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;

    /**
    * 参考:http://javaarm.com/faces/display.xhtml?tid=3109&page=1#post_38375
    */
    @WebServlet("/UploadServlet_demo2")
    @MultipartConfig(
            location="",
            fileSizeThreshold = 1024 * 1024 * 2,
            maxFileSize = 1024 * 1024 * 8,
            maxRequestSize = 1024 * 1024 * 10)

    public class UploadServlet_WithMultipartConfig extends HttpServlet {
        private static final long serialVersionUID = 1L;
       
        public static final int DEFAULT_UPLOAD_maxFileSize = 5242880;
        public static final int DEFAULT_UPLOAD_maxRequestSize = 418018841;
        public static final int DEFAULT_UPLOAD_fileSizeThreshold = 1048576;
       
        public static final String FILED_NAME_targetDirectory = "targetDirectory";
       
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
           
            String targetDirectory = request.getParameter(FILED_NAME_targetDirectory);
            if(targetDirectory!=null){
                System.out.println("Normal!!!");
                System.out.println("If we do declare @MultipartConfig() on UploadServlet, ");
                System.out.println("  all fileds(<input type='text' ... />, <input type='file' .. />) in html from is wrapped into javax.servlet.http.Part,");
                System.out.println("  but they will be unwrapped and injected into this servlet's request, ");
                System.out.println("  so, request.getParameterMap() contains unwrapped fields!");
                System.out.println("(1) We can get parameter by request.getParameter(xxx)");
                System.out.println("(2) Bellow org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(HttpServletRequest) returns empty List!");
            }else{
                printFeedBackInfo(response,"files/requets are too large, all items are ignored!");
                return;
            }

            if (!ServletFileUpload.isMultipartContent(request)) {
                printFeedBackInfo(response,<form>'senctyp must be 'multipart/form-data'!");
                return;
            }

     

     

     

            DiskFileItemFactory factory = new DiskFileItemFactory();

            factory.setSizeThreshold(DEFAULT_UPLOAD_fileSizeThreshold);

            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

           

            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setFileSizeMax(DEFAULT_UPLOAD_maxFileSize);

            upload.setSizeMax(DEFAULT_UPLOAD_maxRequestSize);

           

            StringBuilder sb_success = new StringBuilder("上传成功的文件:<br/>");

            StringBuilder sb_failure = new StringBuilder("上传失败的文件:<br/>");

            try {

                @SuppressWarnings("unchecked")

                List<FileItem> list = (List<FileItem>)upload.parseRequest(request);

               

                if(getParameter(list, FILED_NAME_targetDirectory)!=null){

                    printFeedBackInfo(response,"IMPOSSIBLE: targetDirectory should be null.");

                    return;

                }

               

                if(list==null||list.size()==0){

                    printFeedBackInfo(response,"THIS IS NORMAL!!!");
                    printFeedBackInfo(response,"     You should extract files from the javax.servlet.http.Part directly! Do  not use commons-fileupload-1.2.2.jar and commons-io-2.3.jar!");

                    return;

                }

                //bellow codes will not be run

                File targetDirectoryFile = new File(targetDirectory);

                if(! targetDirectoryFile.exists()){

                    targetDirectoryFile.mkdirs();

                }

               

                Iterator<FileItem> it = list.iterator();

                while (it.hasNext()) {

                    FileItem item = it.next();

                    if (!item.isFormField()) {

                        String fileName = new File(item.getName()).getName();

                        if(fileName==null||fileName.trim().length()==0){

                            //<input type="file" name="file_i" size="60" /> is NOT selected.

                        }else{

                            item.write(new File(targetDirectory,fileName));

                            sb_success.append(fileName).append("<br />");

                        }

                    }

                }

            } catch (Exception ex) {

                printFeedBackInfo(response,"错误:"+ex.getMessage());

                return;

            }

            StringBuilder sb_result = new StringBuilder("上传结果:<br />");
            sb_result.append("(a) ").append(sb_success.toString()).append("<br/>");
            sb_result.append("(b) ").append(sb_failure.toString());
            printFeedBackInfo(response,sb_result.toString());
        }

     

     

        private String getParameter(List<FileItem>list,String parameterName){

            Iterator<FileItem> it = list.iterator();

            while (it.hasNext()) {

                FileItem item = it.next();

                if (!item.isFormField()) {

                    //Ignore File Item!

                }else{

                    if(item.getFieldName().equals(parameterName)){

                        return item.getString();

                    }

                }

            }

            return null;

        }

        private void printFeedBackInfo(HttpServletResponse response,String info) throws IOException{

            PrintWriter writer = response.getWriter();

            writer.println(info);

            writer.flush();

        }

    }

     

     

     

    (b) html form
    <form method="post" action="/UploadServlet_demo2" enctype="multipart/form-data" >

        Directory:  <input type="text" name="targetDirectory" value="/home/ybxiang/file/" size="60" /><br />

        File:<input type="file" name="file1" id="file1" /> <br/>

        File:<input type="file" name="file2" id="file2" /> <br/>

        <input type="submit" value="Upload" name="upload" id="upload" />

    </form>

     

     

     

     

    5.2.2 extract files from javax.servlet.http.HttpServletRequest.getPart(String) directly (success and recommended

    import java.io.*;

    import java.util.logging.Level;

    import java.util.logging.Logger;

     

    import javax.servlet.ServletException;

    import javax.servlet.annotation.MultipartConfig;

    import javax.servlet.annotation.WebServlet;

    import javax.servlet.http.HttpServlet;

    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletResponse;

    import javax.servlet.http.Part;

     

    /**

    * 测试通过!

    *

    * http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html

    * NOTE: file/request size is set to default (MAX).

    */

    @WebServlet("/UploadServlet_demo3")

    @MultipartConfig

    public class UploadServlet_WithMultipartConfig_SunExample extends HttpServlet {

        private static final long serialVersionUID = 1L;

       

        private final static Logger LOGGER =

                Logger.getLogger(UploadServlet_WithMultipartConfig_SunExample.class.getCanonicalName());

       

        public static final String FILED_NAME_targetDirectory = "targetDirectory";

        public static final String FILED_NAME_file1 = "file1";

        //public static final String FILED_NAME_file2 = "file2";

       

        protected void doPost(HttpServletRequest request,

                HttpServletResponse response) throws ServletException, IOException {

            processRequest(request,response);

        }

     

     

        protected void processRequest(HttpServletRequest request,

                HttpServletResponse response)

                throws ServletException, IOException {

            response.setContentType("text/html;charset=UTF-8");

     

            // Create path components to save the file

            final String path = request.getParameter(FILED_NAME_targetDirectory);

            if(path!=null){

                //NORMAL

            }else{

                //FILE is too large!

            }

            File targetDirectoryFile = new File(path);

            if(! targetDirectoryFile.exists()){

                targetDirectoryFile.mkdirs();

            }

           

            final Part filePart = request.getPart(FILED_NAME_file1);

            final String fileName = getFileName(filePart);

     

            OutputStream out = null;

            InputStream filecontent = null;

            final PrintWriter writer = response.getWriter();

     

            try {

                out = new FileOutputStream(new File(path + File.separator
                        + fileName));
                filecontent = filePart.getInputStream();

                int read = 0;
                final byte[] bytes = new byte[1024];

                while ((read = filecontent.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }

                writer.println("New file " + fileName + " created at " + path);

                LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",

                        new Object[]{fileName, path});

            } catch (FileNotFoundException fne) {

                writer.println("You either did not specify a file to upload or are "

                        + "trying to upload a file to a protected or nonexistent "

                        + "location.");

                writer.println("<br/> ERROR: " + fne.getMessage());

     

                LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",

                        new Object[]{fne.getMessage()});

            } finally {

                if (out != null) {

                    out.close();

                }

                if (filecontent != null) {

                    filecontent.close();

                }

                if (writer != null) {

                    writer.close();

                }

            }

        }

     

        private String getFileName(final Part part) {

            final String partHeader = part.getHeader("content-disposition");

            LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);

            for (String content : part.getHeader("content-disposition").split(";")) {

                if (content.trim().startsWith("filename")) {

                    return content.substring(

                            content.indexOf('=') + 1).trim().replace("\"", "");

                }

            }

            return null;

        }

       

        private void printFeedBackInfo(HttpServletResponse response,String info) throws IOException{

            PrintWriter writer = response.getWriter();

            writer.println(info);

            writer.flush();

        }

    }

     

     

     

     

    (b) html form

    <form method="post" action="/UploadServlet_demo3" enctype="multipart/form-data" >

        Directory:  <input type="text" name="targetDirectory" value="/home/ybxiang/file/" size="60" /><br />

        File:<input type="file" name="file1" id="file1" /> <br/>

        File:<input type="file" name="file2" id="file2" /> <br/>

        <input type="submit" value="Upload" name="upload" id="upload" />

    </form>

    )