zoukankan      html  css  js  c++  java
  • Servlet文件上传

    1、环境 : JDK 1.6 , Tomcat 7.0

    2、第三方类库:

        commons-fileupload-1.3.1.jar

        commons-io-2.4.jar

    3、web.xml配置:

    复制代码
    <servlet>
            <servlet-name>FileUpload</servlet-name>
            <servlet-class>java02.rhythmk.com.FileUploadServlet</servlet-class>
    
            <init-param>
                <param-name>filepath</param-name>
                <param-value>uploadfile</param-value>
            </init-param>
            <init-param>
                <param-name>temppath</param-name>
                <param-value>temp</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
            <servlet-name>FileUpload</servlet-name>
            <url-pattern>/FileUpload.html</url-pattern>
        </servlet-mapping>
    复制代码

       4、 jsp :

         

    复制代码
    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Insert title here</title>
    </head>
    <body>
    <!-- enctype 默认是 application/x-www-form-urlencoded -->
         <form action="FileUpload.html" enctype="multipart/form-data" method="post" >
            
                   rhythmk::<input type="text" name="rhythmk"> <br/>
                   上传文件:<input type="file" name="file1"><br/>
    
                  <input type="submit" value="提交"/>
         
         </form>
    
    
    </body>
    </html>
    复制代码

      5、Servlet:

    复制代码
    package java02.rhythmk.com;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.List;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletContext;
    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;
    
    /**
     * Servlet implementation class FileUploadServlet
     */
    @WebServlet("/FileUploadServlet")
    public class FileUploadServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        private static String filepath = "";
        private static String temp = "";
    
        /**
         * Default constructor.
         */
        public FileUploadServlet() {
            // TODO Auto-generated constructor stub
    
        }
    
        @Override
        public void init(ServletConfig config) throws ServletException {
            // TODO Auto-generated method stub
            super.init(config);
    
            if (filepath == "" || temp == "") {
                filepath = config.getInitParameter("filepath");
                temp = config.getInitParameter("temppath");
    
                ServletContext context = getServletContext();
                filepath = context.getRealPath(filepath);
                temp = context.getRealPath(temp);
    
                System.out.println("filepath:" + filepath + ",temp:" + temp);
            }
        }
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
         *      response)
         */
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
         *      response)
         */
    
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
    
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");
    
            try {
    
                DiskFileItemFactory foctory = new DiskFileItemFactory();
    
                // 设置临时文件
                foctory.setRepository(new File(temp));
                // 设置临时文件缓存区大小
                foctory.setSizeThreshold(1024 * 1024);
    
                ServletFileUpload sFileUpload = new ServletFileUpload(foctory);
    
                List<FileItem> list = (List<FileItem>) sFileUpload
                        .parseRequest(request);
    
                for (FileItem item : list) {
                    String name = item.getFieldName();
                    if (item.isFormField()) {
                        System.out.println("filedName:" + name + ",value:"
                                + item.getString());
    
                    } else {
    
                        String filename = item.getName();
    
                        System.out.println("value:" + filename);
    
                        if (filename.length() > 0) {
                            System.out.println("文件保存路径:" + filepath + "\"
                                    + filename);
    
                            File file = new File(filepath);
                            if (!file.exists()) {
                                file.mkdir();
                            }
    
                            // 保存文件
                            item.write(new File(filepath, filename));
    
                            response.getWriter().write(
                                    "文件保存路径:" + filepath + "\" + filename);
                        }
    
                    }
    
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
    }
    复制代码
  • 相关阅读:
    Educational Codeforces Round 10 C. Foe Pairs 水题
    Educational Codeforces Round 10 B. z-sort 构造
    CDOJ 1048 Bob's vector 三分
    Educational Codeforces Round 10 A. Gabriel and Caterpillar 模拟
    第14届电子科大初赛民间盗版部分题目题解
    HDU 5654 xiaoxin and his watermelon candy 离线树状数组 区间不同数的个数
    HDU 5653 Bomber Man wants to bomb an Array. dp
    HDU 5652 India and China Origins 二分+并查集
    HDU 5651 xiaoxin juju needs help 数学
    HDU 5650 so easy 数学
  • 原文地址:https://www.cnblogs.com/hoobey/p/5402531.html
Copyright © 2011-2022 走看看