1、、使用到的jar包,为apache的一个子项目
 此commons-fileupload-1.2.2需要以下commons-io-2.0.1的支持
 

2、页面展示fileUpload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
 
    <title>My JSP 'fileUpload.jsp' starting page</title>
 
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
 
  <body>
    <form action="UploadServlet" method="post" enctype="multipart/form-data">
    username: <input type="text" name="username"><br>
    file: <input type="file" name="file"><br>
    file2: <input type="file" name="file2"><br>
 
    <input type="submit" value="submit">
    </form>
3、servlet处理UploadServlet.java
package com.shengsiyuan.servlet;
 
import java.io.File;
import java.io.IOException;
import java.util.List;
 
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
public class UploadServlet extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        DiskFileItemFactory factory = new DiskFileItemFactory();
 
        String path = req.getRealPath("/upload");//定义上传文件的路径为webroot下的upload文件
 
        factory.setRepository(new File(path));
        factory.setSizeThreshold(1024 * 1024);//上传文件的大小为1024*1024字节,也就是1兆
 
        ServletFileUpload upload = new ServletFileUpload(factory);
 
        try
        {
            List<FileItem> list = (List<FileItem>)upload.parseRequest(req);
 
            for(FileItem item : list)
            {
                String name = item.getFieldName();
 
                if(item.isFormField())//如果上传的是文本域的话,对文本与进行处理
                {
                    String value = item.getString();
 
                    System.out.println(name + "=" + value);
 
                    req.setAttribute(name, value);
                }
                else//如果上传的是文件
                {
                    String value = item.getName();
 
                    int start = value.lastIndexOf("\\");//查找文件名称,从最后一个\开始查找
                    String fileName = value.substring(start + 1);//这时候对应的文件应该从1开始,因为0是\
 
                    req.setAttribute(name, fileName);
 
                    item.write(new File(path, fileName));//将文件写到磁盘上来,path为上传的路径,filename为文件名称
                    //以下是自己写的操作输入输出流的代码,当然也可以不使用下面的写法
//                   
//                    OutputStream os = new FileOutputStream(new File(path, fileName));
//                   
//                    InputStream is = item.getInputStream();
//                   
//                    byte[] buffer = new byte[400];
//                   
//                    int length = 0;
//                   
//                    while((length = is.read(buffer)) != -1)
//                    {
//                        os.write(buffer, 0, length);
//                    }
//                   
//                    is.close();
//                    os.close();
                }
            }
 
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
 
        req.getRequestDispatcher("fileUploadResult.jsp").forward(req, resp);
    }
}
4、结果页fileUploadResult.jsp
<%@ page language="java" import="java.util.*, java.io.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
 
    <title>My JSP 'fileUploadResult.jsp' starting page</title>
 
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
 
  </head>
 
  <body>
 
   <%
   /*
       InputStream is = request.getInputStream();
 
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
  
    String buffer = null; 
 
    while(null != (buffer = br.readLine()))
    {
        out.print(buffer + "<br>");
    }
 
    br.close();
    is.close();
   */
   %>
 
   username : ${requestScope.username }<br>
   file: ${requestScope.file}<br>
   file2: ${requestScope.file2 }<br>
  </body>
</html>
5、页面展示
  结果展示

Servlet实现文件上传(简单)(一)的更多相关文章

  1. Web---演示Servlet的相关类、表单多参数接收、文件上传简单入门

    说明: Servlet的其他相关类: ServletConfig – 代表Servlet的初始化配置参数. ServletContext – 代表整个Web项目. ServletRequest – 代 ...

  2. Servlet实现文件上传

    一.Servlet实现文件上传,需要添加第三方提供的jar包 下载地址: 1) commons-fileupload-1.2.2-bin.zip      :   点击打开链接 2) commons- ...

  3. Servlet实现文件上传,可多文件上传

    一.Servlet实现文件上传,需要添加第三方提供的jar包 接着把这两个jar包放到 lib文件夹下: 二: 文件上传的表单提交方式必须是POST方式, 编码类型:enctype="mul ...

  4. 配置servlet支持文件上传

    Servlet3.0为Servlet添加了multipart配置选项,并为HttpServletRequest添加了getPart和getParts方法获取上传文件.为了使Servlet支付文件上传需 ...

  5. jsp+servlet实现文件上传下载

    相关素材下载 01.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" ...

  6. java commons-fileupload servlet 多文件上传

    commons-fileupload servlet 多文件上传 需要引入的 jar 包. commons-fileupload-1.3.2.jar commons-io-2.2.jar 工程路劲:查 ...

  7. 使用FileUpload实现Servlet的文件上传

    简介 FileUpload 是 Apache commons下面的一个子项目,用来实现Java环境下的文件上传功能. FileUpload链接 FileUpload 是基于Apache的Commons ...

  8. Servlet实现文件上传和下载

    对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用Servlet获取上传文件的输入流然后再解析里面的请求参数是比较麻烦,所以一般选择采用apache的开源工具commo ...

  9. Spring MVC 文件上传简单示例(form、ajax方式 )

    1.Form Upload SpringMVC 中,文件的上传是通过 MultipartResolver 实现的,所以要实现上传,只要注册相应的 MultipartResolver 即可. Multi ...

  10. servlet web文件上传

    web文件上传也是一种POST方式,特别之处在于,需设置FORM的enctype属性为multipart/form-data. 并且需要使用文件域. servlet的代码比较关键是这几句: // 使用 ...

随机推荐

  1. Oracle表和表数据恢复

    Oracle数据库表及表数据的恢复 1. 表恢复 对误删的表,只要没有使用 purge 永久删除选项,那么基本上是能从 flashback table 区恢复回来的. 数据表和其中的数据都是可以恢复回 ...

  2. 完整版getByClass2016/4/20

    function getByclass(parent,sclass) { var re=new RegExp('\\b'+sclass+'\\b','i') var aEli=parent.getEl ...

  3. sql 语句操作

    插入:insert into table1(field1,field2) values(value1,value2) db.execSQL(sql) db.execSQL(sql, bindArgs) ...

  4. Ubuntu 9.10+ apache2.2 +Django的配置

    1.首先安装mod_python apt-get install libapache2-mod-python2.6 (Ubuntu 9.10默认安装的是python 2.6版,如果是2.5可改为 li ...

  5. PAT (Advanced Level) 1100. Mars Numbers (20)

    简单题. #include<cstdio> #include<cstring> #include<cmath> #include<vector> #in ...

  6. AdminLTE的使用

    1.AdminLTE的必要配置文件<!-- Tell the browser to be responsive to screen width --> <meta content=& ...

  7. cordova插件开发-1

    这是初级编,实现了js调用Android代码 首先需要编写java代码: public class AppUpdate extends CordovaPlugin { @Override public ...

  8. 操,escape sequence的输入方法我以前找过一次,这次又忘了,又找了一次,记下来,

    所有的手册和回答都没有说,都是用 echo -e '\e[22;22m,如果不愿意使用echo -e,也可以 输入CvC[[22:22m 不要再忘记了.

  9. TCP/IP网络协议栈(转载)

    原文:http://www.cnblogs.com/xuanku/p/tcpip.html TCP/IP网络协议栈分为四层, 从下至上依次是: 链路层 其实在链路层下面还有物理层, 指的是电信号的传输 ...

  10. maven编码 gbk 的不可映射字符解决办法

    出现这个问题修改一下pom文件的编译配置就好了. <plugin> <groupId>org.apache.maven.plugins</groupId> < ...