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. 项目总结SpringMVC相关

    流程文字概述1.用户发送请求至前端控制器DispatcherServlet2.DispatcherServlet收到请求调用HandlerMapping处理器映射器.3.处理器映射器找到具体的处理器, ...

  2. useradd adduer 的区别

    区别 1). 使用useradd时,如果后面不添加任何参数选项,例如:#sudo useradd test创建出来的用户将是默认“三无”用户:一无Home Directory,二无密码,三无系统She ...

  3. 简单时钟——css3

    这里我们使用css3的特性制作一个简易的时钟,代码如下: <!DOCTYPE html><html> <head> <meta charset="U ...

  4. POJ1182--食物链(经典并查集)并查集看不出来系列2

    食物链 Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 65906   Accepted: 19437 Description ...

  5. HDU 3691 Nubulsa Expo

    无向图的最小割.套了个模板. #include<iostream> #include<cstdio> #include<cstring> #include<a ...

  6. hdu_2159_FATE(完全背包)

    题目连接:hdu_2159_FATE 题意:完全背包的题意 题解:把杀敌数看成背包的容量,维护一个经验的最大值,我是多开一维来记录最大的忍耐度,当然你也可以直接开一位,并记录忍耐度,最后扫一遍 #in ...

  7. JSP文件上传--Smartupload组件

    把smartupload.jar copy到D:\apache-tomcat-7.0.57\lib下. 创建htm上传文件:smartupload_demo01.htm 由于是上传文件,需要对表单进行 ...

  8. Nginx配置-伪静态,隐藏index.php大入口

    server { listen ; server_name ; root E:/www/wvtuan/; index index.php index.html; log_not_found off; ...

  9. LINQ To SQL && Lambda 使用方法小结 (转)

    1. 查询Student表中的所有记录的Sname.Ssex和Class列.select sname,ssex,class from studentLinq: from s in Students   ...

  10. 绑定网关mac,防arp攻击

    netsh i i show innetsh -c i i add neighbors 16 192.168.1.1 08-57-00-51-19-7c