zoukankan      html  css  js  c++  java
  • Servlet实现文件上传,可多文件上传

    一、Servlet实现文件上传,需要添加第三方提供的jar包

    下载地址:

    1) commons-fileupload-1.2.2-bin.zip      :   点击打开链接

    2) commons-io-2.3-bin.zip                       :    点击打开链接    

    接着把这两个jar包放到 lib文件夹下:

    二:

    文件上传的表单提交方式必须是POST方式,

    编码类型:enctype="multipart/form-data",默认是 application/x-www-form-urlencoded

    比如:<form action="FileUpLoad" enctype="multipart/form-data" method="post">

    三、举例:

    1.fileupload.jsp

     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
     2 <%  
     3 String path = request.getContextPath();  
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
     5 %>  
     6   
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
     8 <html>  
     9   <head>  
    10     <base href="<%=basePath%>">  
    11       
    12     <title>My JSP 'fileupload.jsp' starting page</title>  
    13       
    14     <meta http-equiv="pragma" content="no-cache">  
    15     <meta http-equiv="cache-control" content="no-cache">  
    16     <meta http-equiv="expires" content="0">      
    17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    18     <meta http-equiv="description" content="This is my page">  
    19     <!-- 
    20     <link rel="stylesheet" type="text/css" href="styles.css"> 
    21     -->  
    22   
    23   </head>  
    24     
    25   <body>  
    26      <!-- enctype 默认是 application/x-www-form-urlencoded -->  
    27      <form action="FileUpLoad" enctype="multipart/form-data" method="post" >  
    28           
    29                用户名:<input type="text" name="usename"> <br/>  
    30                上传文件:<input type="file" name="file1"><br/>  
    31               上传文件: <input type="file" name="file2"><br/>  
    32               <input type="submit" value="提交"/>  
    33        
    34      </form>  
    35        
    36        
    37        
    38   </body>  
    39 </html>

    2.实际处理文件上传的 FileUpLoad.java

      1 package com.servlet.fileupload;  
      2   
      3 import java.io.File;  
      4 import java.io.*;  
      5 import java.io.IOException;  
      6 import java.io.PrintWriter;  
      7 import java.util.List;  
      8   
      9 import javax.servlet.ServletException;  
     10 import javax.servlet.http.HttpServlet;  
     11 import javax.servlet.http.HttpServletRequest;  
     12 import javax.servlet.http.HttpServletResponse;  
     13   
     14 import org.apache.commons.fileupload.FileItem;  
     15 import org.apache.commons.fileupload.FileUploadException;  
     16 import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
     17 import org.apache.commons.fileupload.servlet.ServletFileUpload;  
     18   
     19 /** 
     20  *  
     21  * @author Administrator 
     22  * 文件上传 
     23  * 具体步骤: 
     24  * 1)获得磁盘文件条目工厂 DiskFileItemFactory 要导包 
     25  * 2) 利用 request 获取 真实路径 ,供临时文件存储,和 最终文件存储 ,这两个存储位置可不同,也可相同 
     26  * 3)对 DiskFileItemFactory 对象设置一些 属性 
     27  * 4)高水平的API文件上传处理  ServletFileUpload upload = new ServletFileUpload(factory); 
     28  * 目的是调用 parseRequest(request)方法  获得 FileItem 集合list , 
     29  *      
     30  * 5)在 FileItem 对象中 获取信息,   遍历, 判断 表单提交过来的信息 是否是 普通文本信息  另做处理 
     31  * 6) 
     32  *    第一种. 用第三方 提供的  item.write( new File(path,filename) );  直接写到磁盘上 
     33  *    第二种. 手动处理   
     34  * 
     35  */  
     36 public class FileUpLoad extends HttpServlet {  
     37   
     38     public void doPost(HttpServletRequest request, HttpServletResponse response)  
     39             throws ServletException, IOException {  
     40           
     41         request.setCharacterEncoding("utf-8");  //设置编码  
     42           
     43         //获得磁盘文件条目工厂  
     44         DiskFileItemFactory factory = new DiskFileItemFactory();  
     45         //获取文件需要上传到的路径  
     46         String path = request.getRealPath("/upload");  
     47           
     48         //如果没以下两行设置的话,上传大的 文件 会占用 很多内存,  
     49         //设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同  
     50         /** 
     51          * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上,  
     52          * 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的  
     53          * 然后再将其真正写到 对应目录的硬盘上 
     54          */  
     55         factory.setRepository(new File(path));  
     56         //设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室  
     57         factory.setSizeThreshold(1024*1024) ;  
     58           
     59         //高水平的API文件上传处理  
     60         ServletFileUpload upload = new ServletFileUpload(factory);  
     61           
     62           
     63         try {  
     64             //可以上传多个文件  
     65             List<FileItem> list = (List<FileItem>)upload.parseRequest(request);  
     66               
     67             for(FileItem item : list)  
     68             {  
     69                 //获取表单的属性名字  
     70                 String name = item.getFieldName();  
     71                   
     72                 //如果获取的 表单信息是普通的 文本 信息  
     73                 if(item.isFormField())  
     74                 {                     
     75                     //获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的  
     76                     String value = item.getString() ;  
     77                       
     78                     request.setAttribute(name, value);  
     79                 }  
     80                 //对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些  
     81                 else  
     82                 {  
     83                     /** 
     84                      * 以下三步,主要获取 上传文件的名字 
     85                      */  
     86                     //获取路径名  
     87                     String value = item.getName() ;  
     88                     //索引到最后一个反斜杠  
     89                     int start = value.lastIndexOf("\");  
     90                     //截取 上传文件的 字符串名字,加1是 去掉反斜杠,  
     91                     String filename = value.substring(start+1);  
     92                       
     93                     request.setAttribute(name, filename);  
     94                       
     95                     //真正写到磁盘上  
     96                     //它抛出的异常 用exception 捕捉  
     97                       
     98                     //item.write( new File(path,filename) );//第三方提供的  
     99                       
    100                     //手动写的  
    101                     OutputStream out = new FileOutputStream(new File(path,filename));  
    102                       
    103                     InputStream in = item.getInputStream() ;  
    104                       
    105                     int length = 0 ;  
    106                     byte [] buf = new byte[1024] ;  
    107                       
    108                     System.out.println("获取上传文件的总共的容量:"+item.getSize());  
    109   
    110                     // in.read(buf) 每次读到的数据存放在   buf 数组中  
    111                     while( (length = in.read(buf) ) != -1)  
    112                     {  
    113                         //在   buf 数组中 取出数据 写到 (输出流)磁盘上  
    114                         out.write(buf, 0, length);  
    115                           
    116                     }  
    117                       
    118                     in.close();  
    119                     out.close();  
    120                 }  
    121             }  
    122               
    123               
    124               
    125         } catch (FileUploadException e) {  
    126             // TODO Auto-generated catch block  
    127             e.printStackTrace();  
    128         }  
    129         catch (Exception e) {  
    130             // TODO Auto-generated catch block  
    131               
    132             //e.printStackTrace();  
    133         }  
    134           
    135           
    136         request.getRequestDispatcher("filedemo.jsp").forward(request, response);  
    137           
    138   
    139     }  
    140   
    141 }

    3.filedemo.jsp

     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
     2 <%  
     3 String path = request.getContextPath();  
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
     5 %>  
     6   
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
     8 <html>  
     9   <head>  
    10     <base href="<%=basePath%>">  
    11       
    12     <title>My JSP 'filedemo.jsp' starting page</title>  
    13       
    14     <meta http-equiv="pragma" content="no-cache">  
    15     <meta http-equiv="cache-control" content="no-cache">  
    16     <meta http-equiv="expires" content="0">      
    17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    18     <meta http-equiv="description" content="This is my page">  
    19     <!-- 
    20     <link rel="stylesheet" type="text/css" href="styles.css"> 
    21     -->  
    22   
    23   </head>  
    24     
    25   <body>  
    26       
    27     用户名:${requestScope.usename } <br/>  
    28     文件:${requestScope.file1 }<br/>  
    29     ${requestScope.file2 }<br/>  
    30     <!-- 把上传的图片显示出来 -->  
    31     <img alt="go" src="upload/<%=(String)request.getAttribute("file1")%> " />  
    32       
    33       
    34       
    35   </body>  
    36 </html>  

    4结果页面:

    Struts2的文件上传与下载  见: http://blog.csdn.net/hzc543806053/article/details/7526306

  • 相关阅读:
    浮动float 摆放位置
    边框(border)宽度样式颜色 和基本属性
    调用css文件,进行调色
    deque_01
    iterator_教程中的讲解
    vector_01
    VS2013_CodeLens
    Qt for Embedded Linux
    jsjl_for_ubuntu12.04
    VC6_导入lib库
  • 原文地址:https://www.cnblogs.com/eaglezb/p/6124571.html
Copyright © 2011-2022 走看看