文件上传之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
    }

}

运行示例

本文转自博客园xingoo的博客,原文链接:文件上传之Apache commons fileupload使用,如需转载请自行联系原博主。

时间: 2024-09-30 05:26:31

文件上传之Apache commons fileupload使用的相关文章

Spring中实现文件上传

实现图片上传  用户必须能够上传图片,因此需要文件上传的功能.比较常见的文件上传组件有Commons FileUpload(http://jakarta.apache.org/commons/fileupload/a>)和COS FileUpload(http://www.servlets.com/cos),Spring已经完全集成了这两种组件,这里我们选择Commons FileUpload.  由于Post一个包含文件上传的Form会以multipart/form-data请求发送给服务器,

commons fileupload实现文件上传的实例代码_java

一.文件上传的原理分析 1.文件上传的必要前提 a.表单的method必须是post b.表单的enctype属性必须是multipart/form-data类型的. enctype默认值:application/x-www-form-urlencoded 作用:告知服务器,请求正文的MIME类型 application/x-www-form-urlencoded : username=abc&password=123 ServletRequest.getParameter(String nam

asp.net fileupload控件上传文件与多文件上传_实用技巧

1.前台文件 Default.aspx: <%@ Page Language="C#" AutoEventWireup="true"CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.

JavaEE组件commons-fileupload实现文件上传、下载_java

一.文件上传概述 实现Web开发中的文件上传功能,需要两步操作: 1.在Web页面中添加上传输入项 <form action="#" method="post" enctype="multipart/form-data"> <input type="file" name="filename1"/><br> <input type="file" n

Java中实现文件上传下载的三种解决方案(推荐)_java

java文件上传与文件下载是程序开发中比较常见的功能,下面通过本文给大家介绍Java中实现文件上传下载的三种解决方案,具体详情如下所示: 第一点:Java代码实现文件上传 FormFile file=manform.getFile(); String newfileName = null; String newpathname=null; String fileAddre="/numUp"; try { InputStream stream = file.getInputStream(

AjaxFileUpload+Struts2实现多文件上传功能

本文重点给大家介绍AjaxFileUpload+Struts2实现多文件上传功能,具体实现代码大家参考下本文. 单文件和多文件的实现区别主要修改两点, 一是插件ajaxfileupload.js里接收file文件ID的方式 二是后台action是数组形式接收 1.ajaxFileUpload文件下载地址http://www.phpletter.com/Demo/AjaxFileUpload-Demo/ 2.引入jquery-1.8.0.min.js.ajaxFileUpload.js文件 3.文

php文件上传经典代码

php文件上传经典代码 function FileUpload( $resourceType, $currentFolder, $sCommand ) {  if (!isset($_FILES)) {   global $_FILES;  }  $sErrorNumber = '0' ;  $sFileName = '' ;  if ( isset( $_FILES['NewFile'] ) && !is_null( $_FILES['NewFile']['tmp_name'] ) )

Apache Commons fileUpload实现文件上传

将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 最简单的例子,通

Apache commons fileupload文件上传实例讲解_java

文件上传的方法主要目前有两个常用的,一个是SmartUpload,一个是Apache的Commons fileupload. 我们这里主要介绍下第二个的用法,首先要上传文件,注意几个问题: 1 form表单内,要添加空间<input type="file" name="myfile"> 2 form表单的内容格式要定义成multipart/form-data格式 3 需要类库:1 commons-io.jar 2commons-fileupload-1.