Apache commons fileupload文件上传实例讲解

 更新时间:2016年10月14日 16:09:58   作者:xingoo  
这篇文章主要为大家详细介绍了Apache commons fileupload文件上传实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

文件上传的方法主要目前有两个常用的,一个是SmartUpload,一个是Apache的Commons fileupload.

我们这里主要介绍下第二个的用法,首先要上传文件,注意几个问题:

  1 form表单内,要添加空间<input type="file" name="myfile">

  2 form表单的内容格式要定义成multipart/form-data格式

  3 需要类库:1 commons-io.jar 2commons-fileupload-1.3.1.jar

接下来我们看下用法。

首先阅读Apache commons fileupload的官方文档可以发现下面几个常用的函数:

1 创建文件解析对象

复制代码 代码如下:
DiskFileUpload diskFileUpload = new DiskFileUpload();

2 进行文件解析后放在List中,因为这个类库支持多个文件上传,因此把结果会存在List中。

复制代码 代码如下:
List<FileItem> list = diskFileUpload.parseRequest(request);

3 获取上传文件,进行分析(不是必须)

复制代码 代码如下:
File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));

4 创建新对象,进行流拷贝

file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
            file1.getParentFile().mkdirs();
            file1.createNewFile();
            
            InputStream ins = fileItem.getInputStream();
            OutputStream ous = new FileOutputStream(file1);
            
            try{
              byte[] buffer = new byte[1024];
              int len = 0;
              while((len = ins.read(buffer)) > -1)
                ous.write(buffer,0,len);
              out.println("以保存文件"+file1.getAbsolutePath()+"<br/>");
            }finally{
              ous.close();
              ins.close();
            }

这样我们就完成了文件的上传。

fileUpload.html

 <form action="servlet/UploadServlet" method="post" enctype="multipart/form-data">
    <div align="center">
      <fieldset style="width:80%">
        <legend>上传文件</legend><br/>
          <div align="left">上传文件1</div>
          <div align="left">
            <input type="file" name="file1"/>
          </div>
          <div align="left">上传文件2</div>
          <div align="left">
            <input type="file" name="file2"/>
          </div>
          <div>
            <div align='left'>上传文件说明1</div>
            <div align='left'><input type="text" name="description1"/></div>
          </div>
          <div>
            <div align='left'>上传文件说明2</div>
            <div align='left'><input type="text" name="description2"/></div>
          </div>
          <div>
            <div align='left'>
              <input type='submit' value="上传文件"/>
            </div>
          </div>
      </fieldset>
    </div>
  </form>

web.xml

<servlet>
  <servlet-name>UploadServlet</servlet-name>
  <servlet-class>com.test.hello.UploadServlet</servlet-class>
 </servlet>
<servlet-mapping>
  <servlet-name>UploadServlet</servlet-name>
  <url-pattern>/servlet/UploadServlet</url-pattern>
 </servlet-mapping>

UploadServlet.java

package com.test.hello;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
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.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

public class UploadServlet extends HttpServlet {

  /**
   * Constructor of the object.
   */
  public UploadServlet() {
    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 {

    response.setCharacterEncoding("UTF-8");
    response.getWriter().println("请以POST方式上传文件");
  }

  /**
   * 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
   */
  @SuppressWarnings({ "unchecked", "deprecation" })
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    File file1 = null,file2=null;
    String description1 = null,description2 = null;
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    
    DiskFileUpload diskFileUpload = new DiskFileUpload();
    try{
      List<FileItem> list = diskFileUpload.parseRequest(request);
      
      out.println("遍历所有的FileItem...<br/>");
      for(FileItem fileItem : list){
        if(fileItem.isFormField()){
          if("description1".equals(fileItem.getFieldName())){
            out.println("遍历到description1 ... <br/>");
            description1 = new String(fileItem.getString().getBytes(),"UTF-8");
          }
          if("description2".equals(fileItem.getFieldName())){
            out.println("遍历到description2 ... <br/>");
            description2 = new String(fileItem.getString().getBytes(),"UTF-8");
          }
        }else{
          if("file1".equals(fileItem.getFieldName())){
            File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
            out.println("遍历到file1...<br/>");
            out.println("客户端文件位置:"+remoteFile.getAbsolutePath()+"<br/>");
            
            file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
            file1.getParentFile().mkdirs();
            file1.createNewFile();
            
            InputStream ins = fileItem.getInputStream();
            OutputStream ous = new FileOutputStream(file1);
            
            try{
              byte[] buffer = new byte[1024];
              int len = 0;
              while((len = ins.read(buffer)) > -1)
                ous.write(buffer,0,len);
              out.println("以保存文件"+file1.getAbsolutePath()+"<br/>");
            }finally{
              ous.close();
              ins.close();
            }
          }
          if("file2".equals(fileItem.getFieldName())){
            File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
            out.println("遍历到file2...<br/>");
            out.println("客户端文件位置:"+remoteFile.getAbsolutePath()+"<br/>");
            
            file2 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
            file2.getParentFile().mkdirs();
            file2.createNewFile();
            
            InputStream ins = fileItem.getInputStream();
            OutputStream ous = new FileOutputStream(file2);
            
            try{
              byte[] buffer = new byte[1024];
              int len = 0;
              while((len = ins.read(buffer)) > -1)
                ous.write(buffer,0,len);
              out.println("以保存文件"+file2.getAbsolutePath()+"<br/>");
            }finally{
              ous.close();
              ins.close();
            }
          }
        }
        out.println("Request 解析完毕<br/><br/>");
      }
    }catch(FileUploadException e){}
    
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
    out.println("<HTML>");
    out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
    out.println(" <BODY>");
    
    if(file1 != null){
      out.println("<div>");
      out.println(" <div align='left'>file1;</div>");
      out.println(" <div align='left'><a href='"+request.getContextPath()+"/attachment/"+
          file1.getName()+"'target=_blank>"+file1.getName()+"</a>");
      out.println("</div>");
      out.println("</div>");
    }
    if(file2 != null){
      out.println("<div>");
      out.println(" <div align='left'>file2;</div>");
      out.println(" <div align='left'><a href='"+request.getContextPath()+"/attachment/"+
          file2.getName()+"'target=_blank>"+file2.getName()+"</a>");
      out.println("</div>");
      out.println("</div>");
    }
    out.println("<div>");
    out.println(" <div align='left'>description1:</div>");
    out.println(" <div align='left'>");
    out.println(description1);
    out.println("</div>");
    out.println("</div>");
    
    out.println("<div>");
    out.println(" <div align='left'>description2:</div>");
    out.println(" <div align='left'>");
    out.println(description2);
    out.println("</div>");
    out.println("</div>");
    
    out.println(" </BODY>");
    out.println("</HTML>");
    out.flush();
    out.close();
  }

  /**
   * Initialization of the servlet. <br>
   *
   * @throws ServletException if an error occurs
   */
  public void init() throws ServletException {
    // Put your code here
  }

}

运行示例

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • java简单工厂模式实例及讲解

    java简单工厂模式实例及讲解

    这篇文章主要为大家详细介绍了java简单工厂模式实例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • Java使用ES Client 调用滚动查询及Elasticsearch滚动查询Scrolling机制

    Java使用ES Client 调用滚动查询及Elasticsearch滚动查询Scrolling机制

    Elasticsearch提供了一种称为"滚动查询"(Scrolling)的机制,用于处理大型数据集的分页查询,这篇文章给大家介绍滚动查询的一般步骤及Java使用ESClient调用滚动查询的方法,感兴趣的朋友一起看看吧
    2023-08-08
  • Java多线程CAS操作原理代码实例解析

    Java多线程CAS操作原理代码实例解析

    这篇文章主要介绍了Java多线程CAS操作原理代码实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • Mybatis 动态sql if 判读条件等于一个数字的案例

    Mybatis 动态sql if 判读条件等于一个数字的案例

    这篇文章主要介绍了Mybatis 动态sql if 判读条件等于一个数字的案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-11-11
  • Java中的CountDownLatch闭锁详解

    Java中的CountDownLatch闭锁详解

    这篇文章主要介绍了Java中的CountDownLatch闭锁详解,CountDownLatch用给定的计数初始化,await属于阻塞方法,直到当前计数达到零,由于countDown方法被调用,然后释放所有await等待的线程,并立即返回线程后续的await调用逻辑,需要的朋友可以参考下
    2023-12-12
  • 解决异常FileNotFoundException:class path resource找不到资源文件的问题

    解决异常FileNotFoundException:class path resource找不到资源文件的问题

    今天小编就为大家分享一篇关于解决异常FileNotFoundException:class path resource找不到资源文件的问题,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-12-12
  • java常见报错:Array Out of Bounds两种解决办法

    java常见报错:Array Out of Bounds两种解决办法

    这篇文章主要给大家介绍了关于java报错Array Out of Bounds的两种解决办法,Array out of bounds错误表示你尝试访问数组中不存在的索引,即索引小于零或者大于等于数组的大小,文中通过代码将解决的办法介绍的非常详细,需要的朋友可以参考下
    2024-08-08
  • 详解MyBatis的XML实现方法(附带注解方式实现)

    详解MyBatis的XML实现方法(附带注解方式实现)

    这篇文章主要详细介绍了MyBatis的XML实现方法(附带注解方式实现),文中通过代码示例给大家讲解的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
    2024-05-05
  • 解决Properties属性文件中的值有等号和换行的小问题

    解决Properties属性文件中的值有等号和换行的小问题

    这篇文章主要介绍了解决Properties属性文件中的值有等号有换行的小问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08
  • Spring Boot在开发过程中常用IDEA插件

    Spring Boot在开发过程中常用IDEA插件

    这篇文章主要为大家介绍了Spring Boot在开发过程中常用IDEA插件,帮助大家提高开发工作效率,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2022-03-03

最新评论