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();
        }

    }

}
复制代码
posted @ 2016-04-17 22:18  starskyhu  阅读(286)  评论(0编辑  收藏  举报