专栏首页xingoo, 一个梦想做发明家的程序员文件上传之Apache commons fileupload使用

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

}

运行示例

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Java程序员的日常 —— static的用法讲解实践

    之前文章说过Java中static的作用,有朋友想看个例子。于是便抽空写了个小栗子 代码 package xing.test.thinking.chap5...

    用户1154259
  • 【AngularJS】—— 12 独立作用域

    前面通过视频学习了解了指令的概念,这里学习一下指令中的作用域的相关内容。 通过独立作用域的不同绑定,可以实现更具适应性的自定义标签。借由不同的绑定规则绑定属...

    用户1154259
  • 手把手教你Dojo入门

    如果仅仅是为了练习Dojo,或者进行测试,可以参考下面的步骤。下面的文件均是在Windows下测试 需要的工具 1 Tomcat服务器:下载地址 选择适合自己的...

    用户1154259
  • VeeValidate 的使用场景以及配置

    这个例子中发验证码是一个验证 注册又是一个验证 所以有点意义! 在发送验证码的时候需要验证手机号码和图形验证码 注册的时候需要验证除图形验证码之外的数据

    李昊天
  • 多栏布局与JS实现瀑布流

    css3属性之多栏布局与JS实现瀑布流    背景:之前打算自己总结一下flex布局的知识点,发现自己无从下手,原因在何处:我反思了一下,其实原因很简单,使用的...

    okaychen
  • MVC中实现加载更多

    需要实现的功能: 数据太多想初次加载部分数据,在底部加上“加载更多”按钮 点击后加载第二页数据(从数据库只取指定页数据)后接在已有数据后面(类似于android...

    欢醉
  • JSX渲染原理

    1.基于babel-preset-react-app这个语法解析包,把jsx语法转换成一个名为 React.createElement() 的方法调用。

    柴小智
  • 从头搭建一个在线聊天室(一)

    今天从头开始做一个在线聊天网站,网上各种各样的聊天工具已经很多了,为啥还要做这么一个聊天工具呢,无他,兴趣耳!

    周萝卜
  • [前端][css]float left布局换行不正常问题

    最近遇到一个页面布局上的问题,后来模拟了一下还原了下出现的原因。本来大概想实现的布局大概是这样的

    Tuzei
  • 一起学爬虫——使用xpath库爬取猫眼电

    之前分享了一篇使用requests库爬取豆瓣电影250的文章,今天继续分享使用xpath爬取猫眼电影热播口碑榜

    py3study

扫码关注云+社区

领取腾讯云代金券