Apache Commons fileUpload实现文件上传

2024-06-11 19:48

本文主要是介绍Apache Commons fileUpload实现文件上传,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

/*2013-9-9*/

/*http://zhangjunhd.blog.51cto.com/113473/18331*/


Apache的commons-fileupload.jar可方便的实现文件的上传功能,本文通过实例来介绍如何使用commons-fileupload.jar。


    将Apache的commons-fileupload.jar放在应用程序的WEB-INF\lib下,即可使用。下面举例介绍如何使用它的文件上传功能。
所使用的fileUpload版本为1.2,环境为Eclipse3.3+MyEclipse6.0。FileUpload 是基于 Commons IO的,所以在进入项目前先确定Commons IO的jar包(本文使用commons-io-1.3.2.jar)在WEB-INF\lib下。
此文作示例工程可在文章最后的附件中下载。
示例1
最简单的例子,通过ServletFileUpload静态类来解析Request,工厂类FileItemFactory会对mulipart类的表单中的所有字段进行处理,不只是file字段。getName()得到文件名,getString()得到表单数据内容,isFormField()可判断是否为普通的表单项。
demo1.html
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>File upload</title>
</head>
<body>
       //必须是multipart的表单数据。
    <form name="myform" action="demo1.jsp" method="post"
       enctype="multipart/form-data">
       Your name: <br>
       <input type="text" name="name" size="15"><br>
       File:<br>
       <input type="file" name="myfile"><br>
       <br>
       <input type="submit" name="submit" value="Commit">
    </form>
</body>
</html>
 
demo1.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);//检查输入请求是否为multipart表单数据。
    if (isMultipart == true) {
       FileItemFactory factory = new DiskFileItemFactory();//为该请求创建一个DiskFileItemFactory对象通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。
       ServletFileUpload upload = new ServletFileUpload(factory);
       List<FileItem> items = upload.parseRequest(request);
       Iterator<FileItem> itr = items.iterator();
       while (itr.hasNext()) {
           FileItem item = (FileItem) itr.next();
           //检查当前项目是普通表单项目还是上传文件。
           if (item.isFormField()) {//如果是普通表单项目,显示表单内容。
       String fieldName = item.getFieldName();
       if (fieldName.equals("name")) //对应demo1.htmltype="text" name="name"
           out.print("the field name is" + item.getString());//显示表单内容。
       out.print("<br>");
           } else {//如果是上传文件,显示文件名。
       out.print("the upload file name is" + item.getName());
       out.print("<br>");
           }
       }
    } else {
       out.print("the enctype must be multipart/form-data");
    }
%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>File upload</title>
</head>
<body>
</body>
</html>
结果:
the field name isjeff
the upload file name isD:\C语言考试样题\作业题.rar
示例2
上传两个文件到指定的目录。
demo2.html
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>File upload</title>
</head>
<body>
    <form name="myform" action="demo2.jsp" method="post"
       enctype="multipart/form-data">
       File1:<br>
       <input type="file" name="myfile"><br>
       File2:<br>
       <input type="file" name="myfile"><br>
       <br>
       <input type="submit" name="submit" value="Commit">
    </form>
</body>
</html>
 
demo2.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%String uploadPath="D:\\temp";
  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  if(isMultipart==true){
      try{
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);//得到所有的文件
       Iterator<FileItem> itr = items.iterator();
        while(itr.hasNext()){//依次处理每个文件
         FileItem item=(FileItem)itr.next();
         String fileName=item.getName();//获得文件名,包括路径
         if(fileName!=null){
             File fullFile=new File(item.getName());
             File savedFile=new File(uploadPath,fullFile.getName());
             item.write(savedFile);
         }
        }
        out.print("upload succeed");
      }
      catch(Exception e){
         e.printStackTrace();
      }
  }
  else{
      out.println("the enctype must be multipart/form-data");
  }
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
</body>
</html>
结果:
upload succeed
此时,在"D:\temp"下可以看到你上传的两个文件。
示例3
上传一个文件到指定的目录,并限定文件大小。
demo3.html
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>File upload</title>
</head>
<body>
    <form name="myform" action="demo3.jsp" method="post"
       enctype="multipart/form-data">
       File:<br>
       <input type="file" name="myfile"><br>
       <br>
       <input type="submit" name="submit" value="Commit">
    </form>
</body>
</html>
 
demo3.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
    File uploadPath = new File("D:\\temp");//上传文件目录
    if (!uploadPath.exists()) {
       uploadPath.mkdirs();
    }
    // 临时文件目录
    File tempPathFile = new File("d:\\temp\\buffer\\");
    if (!tempPathFile.exists()) {
       tempPathFile.mkdirs();
    }
    try {
       // Create a factory for disk-based file items
       DiskFileItemFactory factory = new DiskFileItemFactory();
 
       // Set factory constraints
       factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
       factory.setRepository(tempPathFile);//设置缓冲区目录
 
       // Create a new file upload handler
       ServletFileUpload upload = new ServletFileUpload(factory);
 
       // Set overall request size constraint
       upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB
 
       List<FileItem> items = upload.parseRequest(request);//得到所有的文件
       Iterator<FileItem> i = items.iterator();
       while (i.hasNext()) {
           FileItem fi = (FileItem) i.next();
           String fileName = fi.getName();
           if (fileName != null) {
       File fullFile = new File(fi.getName());
       File savedFile = new File(uploadPath, fullFile
              .getName());
       fi.write(savedFile);
           }
       }
       out.print("upload succeed");
    } catch (Exception e) {
       e.printStackTrace();
    }
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
</body>
</html>
示例4
利用Servlet来实现文件上传。
Upload.java
package com.zj.sample;
 
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
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;
 
@SuppressWarnings("serial")
public class Upload extends HttpServlet {
    private String uploadPath = "D:\\temp"; // 上传文件的目录
    private String tempPath = "d:\\temp\\buffer\\"; // 临时文件目录
    File tempPathFile;
 
    @SuppressWarnings("unchecked")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
           throws IOException, ServletException {
       try {
           // Create a factory for disk-based file items
           DiskFileItemFactory factory = new DiskFileItemFactory();
 
           // Set factory constraints
           factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
           factory.setRepository(tempPathFile);// 设置缓冲区目录
 
           // Create a new file upload handler
           ServletFileUpload upload = new ServletFileUpload(factory);
 
           // Set overall request size constraint
           upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB
 
           List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
           Iterator<FileItem> i = items.iterator();
           while (i.hasNext()) {
              FileItem fi = (FileItem) i.next();
              String fileName = fi.getName();
              if (fileName != null) {
                  File fullFile = new File(fi.getName());
                  File savedFile = new File(uploadPath, fullFile.getName());
                  fi.write(savedFile);
              }
           }
           System.out.print("upload succeed");
       } catch (Exception e) {
           // 可以跳转出错页面
           e.printStackTrace();
       }
    }
 
    public void init() throws ServletException {
       File uploadFile = new File(uploadPath);
       if (!uploadFile.exists()) {
           uploadFile.mkdirs();
       }
       File tempPathFile = new File(tempPath);
        if (!tempPathFile.exists()) {
           tempPathFile.mkdirs();
       }
    }
}
 
demo4.html
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>File upload</title>
</head>
<body>
// action="fileupload"对应web.xml<servlet-mapping><url-pattern>的设置.
    <form name="myform" action="fileupload" method="post"
       enctype="multipart/form-data">
       File:<br>
       <input type="file" name="myfile"><br>
       <br>
       <input type="submit" name="submit" value="Commit">
    </form>
</body>
</html>
 
web.xml
<servlet>
    <servlet-name>Upload</servlet-name>
    <servlet-class>com.zj.sample.Upload</servlet-class>
</servlet>
 
<servlet-mapping>
    <servlet-name>Upload</servlet-name>
    <url-pattern>/fileupload</url-pattern>
</servlet-mapping>

这篇关于Apache Commons fileUpload实现文件上传的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1052128

相关文章

SpringBoot实现微信小程序支付功能

《SpringBoot实现微信小程序支付功能》小程序支付功能已成为众多应用的核心需求之一,本文主要介绍了SpringBoot实现微信小程序支付功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作... 目录一、引言二、准备工作(一)微信支付商户平台配置(二)Spring Boot项目搭建(三)配置文件

基于Python实现高效PPT转图片工具

《基于Python实现高效PPT转图片工具》在日常工作中,PPT是我们常用的演示工具,但有时候我们需要将PPT的内容提取为图片格式以便于展示或保存,所以本文将用Python实现PPT转PNG工具,希望... 目录1. 概述2. 功能使用2.1 安装依赖2.2 使用步骤2.3 代码实现2.4 GUI界面3.效

MySQL更新某个字段拼接固定字符串的实现

《MySQL更新某个字段拼接固定字符串的实现》在MySQL中,我们经常需要对数据库中的某个字段进行更新操作,本文就来介绍一下MySQL更新某个字段拼接固定字符串的实现,感兴趣的可以了解一下... 目录1. 查看字段当前值2. 更新字段拼接固定字符串3. 验证更新结果mysql更新某个字段拼接固定字符串 -

java实现延迟/超时/定时问题

《java实现延迟/超时/定时问题》:本文主要介绍java实现延迟/超时/定时问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java实现延迟/超时/定时java 每间隔5秒执行一次,一共执行5次然后结束scheduleAtFixedRate 和 schedu

Java Optional避免空指针异常的实现

《JavaOptional避免空指针异常的实现》空指针异常一直是困扰开发者的常见问题之一,本文主要介绍了JavaOptional避免空指针异常的实现,帮助开发者编写更健壮、可读性更高的代码,减少因... 目录一、Optional 概述二、Optional 的创建三、Optional 的常用方法四、Optio

在Android平台上实现消息推送功能

《在Android平台上实现消息推送功能》随着移动互联网应用的飞速发展,消息推送已成为移动应用中不可或缺的功能,在Android平台上,实现消息推送涉及到服务端的消息发送、客户端的消息接收、通知渠道(... 目录一、项目概述二、相关知识介绍2.1 消息推送的基本原理2.2 Firebase Cloud Me

Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能

《SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能》:本文主要介绍SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能,本文分步骤给大家介绍的... 目录原理解析1. mysql主从复制(Master-Slave Replication)2. 读写分离3.

Redis实现延迟任务的三种方法详解

《Redis实现延迟任务的三种方法详解》延迟任务(DelayedTask)是指在未来的某个时间点,执行相应的任务,本文为大家整理了三种常见的实现方法,感兴趣的小伙伴可以参考一下... 目录1.前言2.Redis如何实现延迟任务3.代码实现3.1. 过期键通知事件实现3.2. 使用ZSet实现延迟任务3.3

基于Python和MoviePy实现照片管理和视频合成工具

《基于Python和MoviePy实现照片管理和视频合成工具》在这篇博客中,我们将详细剖析一个基于Python的图形界面应用程序,该程序使用wxPython构建用户界面,并结合MoviePy、Pill... 目录引言项目概述代码结构分析1. 导入和依赖2. 主类:PhotoManager初始化方法:__in

springboot filter实现请求响应全链路拦截

《springbootfilter实现请求响应全链路拦截》这篇文章主要为大家详细介绍了SpringBoot如何结合Filter同时拦截请求和响应,从而实现​​日志采集自动化,感兴趣的小伙伴可以跟随小... 目录一、为什么你需要这个过滤器?​​​二、核心实现:一个Filter搞定双向数据流​​​​三、完整代码