码迷,mamicode.com
首页 > 其他好文 > 详细

上传文件的表单

时间:2014-05-22 15:09:24      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   class   c   code   

1、使用Apache 的 Commons FileUpload

      FileUpload下载地址:

  http://commons.apache.org/fileupload/

  下载:commons-fileupload-1.2.2-bin.zip    得到:commons-fileupload-1.2.2.jar

  http://commons.apache.org/io/

  下载:commons-io-1.4-bin.zip       得到:commons-io-1.4.jar

2、web.xml配置上传的文件所在的文件夹名称uploads,同时要在webroot下新建这个文件夹uploads

 

bubuko.com,布布扣
<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>up</servlet-name>
    <servlet-class>test.up</servlet-class>
   <!--一组键值对。设置初始化参数-->
    <init-param>
     <param-name>savePath</param-name>
     <param-value>uploads</param-value>
    </init-param>
  </servlet>
bubuko.com,布布扣

3、表单

bubuko.com,布布扣
<form method="POST" enctype="multipart/form-data" action="./servlet/up">
  File to upload: <input type="file" name="upfile"><br/>
  Notes about the file: <input type="text" name="note"><br/>
  <br/>
  <input type="submit" value="Press"> to upload the file!
</form>
bubuko.com,布布扣

4、servlet

注意init();

bubuko.com,布布扣
package test;

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

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class up extends HttpServlet {
    private ServletContext sc;
    private String savePath;

    /**
     * Constructor of the object.
     */
    public up() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> items = upload.parseRequest(request);
            for(FileItem item:items) {
                // 判断是否普通的表单数据
                if (item.isFormField()) {
                    System.out.println("表单参数名:" + item.getFieldName()
                            + ",表单参数值:" + item.getString("UTF-8"));
                } else {
                    if (item.getName() != null && !item.getName().equals("")) {
                        System.out.println("上传文件的大小:" + item.getSize());
                        System.out.println("上传文件的类型:" + item.getContentType());
                        // item.getName()返回上传文件在客户端的完整路径名称
                        System.out.println("上传文件的名称:" + item.getName());

                        File tempFile = new File(item.getName());
                        // 上传文件的保存路径
                        File file = new File(sc.getRealPath("/") + savePath,
                                tempFile.getName());
                        item.write(file);
                        request.setAttribute("upload.message", "上传文件成功!");
                    } else {
                        request.setAttribute("upload.message", "没有选择上传文件!");
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("upload.message", "上传文件失败!");
        }
        request.getRequestDispatcher("/rs.jsp").forward(request, response);
    }

    /*
     * 会被自动执行 参数ServletConfig,即在web.xml中配置的信息
     */
    public void init(ServletConfig config) {
        // 在web.xml中设置的一个初始化参数
        savePath = config.getInitParameter("savePath");
        sc = config.getServletContext();
    }

}
bubuko.com,布布扣

 

Done

上传文件的表单,布布扣,bubuko.com

上传文件的表单

标签:des   style   blog   class   c   code   

原文地址:http://www.cnblogs.com/xingyyy/p/3744119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!