the5fire

关注Python、Django、Vim、Linux、Web开发、团队管理和互联网--Life is short, we need Python.


JSP上传文件简单实现(commons-fileupload)

作者:the5fire | 标签:     | 发布:2011-01-05 10:01 a.m. | 阅读量: 24877, 23429

网上相关的例子比较多,这里只给出最简单的一个,使用commons-fileupload组件完成上传。首先你需要下载组件,按说从官网上下载文件应该就可以了,不过貌似最新的这个少了一个jar包,所以我往网盘里传了一份,大家自行下载: http://u.115.com/file/f4694e2ffc http://u.115.com/file/f4e87888d0 ,把这俩文件放到工程WEN-INF的lib目录下。

首先建立一个Servlet:UploadServlet.java:

.. code:: java

package com.web;
import java.io.IOException;
import java.io.PrintWriter;

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

import org.apache.commons.fileupload.*;
import java.util.*;
import java.io.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

/**
 * 上传文件的Servlet
 * @author 胡阳
 *
 */
public class UploadServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        System.out.println("dddd");
        res.setContentType("text/html; charset=GB18030");
        PrintWriter out = res.getWriter();
        System.out.println(req.getContentLength());
        System.out.println(req.getContentType());
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 允许设置内存中存储数据的门限,单位:字节
        factory.setSizeThreshold(4096);

        // 如果文件大小大于SizeThreshold,则保存到临时目录
        factory.setRepository(new File("D:\\"));
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 最大上传文件,单位:字节
        upload.setSizeMax(1000000);

        try {
            List fileItems = upload.parseRequest(req);
            Iterator iter = fileItems.iterator();

            if (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fileName = item.getName();
                // 忽略其他不是文件域的所有表单信息
                if (!item.isFormField()) {
                        try {
                            //取得文件名
                            fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
                            // 保存上传的文件到指定的目录指定文件名中
                            item.write(new File("D:\\",fileName));

                        } catch (Exception e) {
                            out.println(e);
                        }
                } else {
                        throw new IOException("fail to upload");
                }
            }
        } catch (FileUploadException e) {
            out.println(e);
        }
    }
}

然后是web.xml文件:

::

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.web.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/servlet/UploadServlet</url-pattern>
  </servlet-mapping>
</web-app>

上传文件的页面:upload.jsp

::

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!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=GB18030">
<title>Insert title here</title>
</head>
<body>
//注意action地址,还有enctype要写成multipart/form-data,和method="POST"    
<form name="uploadform" method="POST" action="./servlet/UploadServlet" ENCTYPE="multipart/form-data">

        <table border="1" width="450" cellpadding="4" cellspacing="2" bordercolor="#9BD7FF">
        <tr>
            <td width="100%" colspan="2">

                            文件:<input name="x" size="40" type="file">

            </td>
        </tr>
        </table>
        <br/><br/>

        <table>
        <tr><td align="center"><input name="upload" type="submit" value="开始上传"/></td></tr>
        </table>

</form>
</body>
</html>

更多内容可以参考这里:http://www.blogjava.net/freeman1984/archive/2007/09/28/149358.html

- from the5fire.com
----EOF-----

微信公众号:Python程序员杂谈

【上一篇】 随机日志:两列显示
【下一篇】 js的日期控件

其他分类: