当前位置: 移动技术网 > IT编程>开发语言>Java > servlet上传文件实现代码详解(四)

servlet上传文件实现代码详解(四)

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了servlet上传文件的具体代码,供大家参考,具体内容如下

1.servlet上传文件

  servlet上传文件就是将客户端的文件上传到服务器端。

  向服务器发送数据时,客户端发送的http请求正文采用“multipart/form-data”数据类型,他表示复杂的多个子部分的复合表单。

  为了简化“multipart/form-data”数据的处理过程。可以使用apache组织提供是的两个开源包来来实现上传。

    fileupload软件包(commons-fileupload-1.2.1.jar),负责文件上传的软件包。

    io软件包(commons-io-1.4.jar)负责输入输出的软件包。

2.servlet上传文件相关类

  2.1fileupload软件包把请求正文包含的复合表单的每个子部分看做fileitem对象。fileitem对象分为两种类型。

    (1)formfiled:普通表单域类型,如表单中的文本和按钮等。

    (2)非formfiled:上传文件类型,表单中的文件域就是这种类型。

  2.2fileitemfactory接口和fileitem接口

     fileitemfactory 是创建fileitem 对象的工厂。

     diskfileitemfactory 实现了fileitemfactory接口,diskfileitemfactory用于创建diskfileitem对象。

     diskfileitem对象用于把客户端上传的文件保存在客户端。

  2.3servletfileupload 类

    servletfileupload为文件上传处理器。和diskfileitemfactory对象关联。

3.上传文件案例

上传文件页面(upload.html)

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>title</title>
</head>
<body>
<form action="upload" enctype="multipart/form-data" method="post">
  <input name="username" size="30">
  <input type="file" name="file1" size="30">
  <input type="file" name="file2" size="30">
  <input type="submit" name="submit" value="upload">
</form>
</body>
</html>

上传文件的servlet类

package com.learn;

import org.apache.commons.fileupload.fileitem;
import org.apache.commons.fileupload.fileuploadexception;
import org.apache.commons.fileupload.disk.diskfileitemfactory;
import org.apache.commons.fileupload.servlet.servletfileupload;
import org.apache.poi.common.usermodel.linestyle;

import javax.servlet.servletconfig;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.file;
import java.io.ioexception;
import java.io.printwriter;
import java.util.iterator;
import java.util.list;


public class servletupload extends httpservlet {

  private string filepath;
  private string tempfilepath;
  @override
  public void init(servletconfig config) throws servletexception {
    super.init(config);
    //获取类文件路径初始化值
    filepath = config.getinitparameter("filepath");
    tempfilepath = config.getinitparameter("tempfilepath");
    system.out.println("init filepath:"+filepath);
    system.out.println("tempfilepath:"+tempfilepath);

    //获取文件路径真实值
    filepath = config.getservletcontext().getrealpath(filepath);
    tempfilepath = config.getservletcontext().getrealpath(tempfilepath);
    system.out.println("realpath:"+filepath);
    system.out.println("tempfilepath"+tempfilepath);


  }


  @override
  protected void dopost(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {
    super.dopost(req, resp);
    //设置返回内容为纯文字内容
    resp.setcontenttype("text/plain");
    resp.setcharacterencoding("utf-8");
    //获取输出对象
    printwriter out = resp.getwriter();

    //创建一个基于硬盘的fileitem工厂
    diskfileitemfactory diskfileitemfactory = new diskfileitemfactory();
    //设置向硬盘写数据的缓冲区大小,这里为4k
    diskfileitemfactory.setsizethreshold(4*1024);
    //设置临时目录
    diskfileitemfactory.setrepository(new file(tempfilepath));

    //创建一个文件上传处理器
    servletfileupload servletfileupload = new servletfileupload(diskfileitemfactory);
    //设置文件上传的大小
    servletfileupload.setsizemax(4*1024*1024);
    //获取参数
    try {
      //获取表单参数
      list list = servletfileupload.parserequest(req);
      //获取迭代器
      iterator iterator = list.iterator();
      //迭代列表
      while(iterator.hasnext()){

        //将参数转型为fileitem类型
        fileitem fileitem = (fileitem) iterator.next();
        if(fileitem.isformfield()){
          system.out.println("处理表单非文件类型数据");
          processformfiled(fileitem,out);
        } else {
          system.out.println("处理吧表单文件类型数据");
          processuploadfile( fileitem,out);
        }

      }
      system.out.println("关闭输出流");
      out.close();

    } catch (fileuploadexception e) {
      e.printstacktrace();
    } catch (exception e) {
      e.printstacktrace();
    }
  }

  private void processformfiled(fileitem fileitem,printwriter printwriter){
    //获取表单域的名称
    string name = fileitem.getname();
    //获取表单域的值
    string value = fileitem.getstring();
    printwriter.print("name:"+name+"value:"+value);

  }

  private void processuploadfile(fileitem fileitem,printwriter printwriter) throws exception {

    //获取文件名称
    string filename = fileitem.getname();
    int i = filename.lastindexof("\\");
    filename = filename.substring(i+1,filename.length());
    //获取文件大小
    long filesize = fileitem.getsize();
    system.out.println("filename:"+filename+"| filesize:"+filesize);
    if("".equals(filename) && filesize == 0)
      return;
    //将文件写入指定位置
    file upload = new file(filepath+file.separator+filename);
    fileitem.write(upload);
    //输出结果
    printwriter.print(filename+"is saved");
    system.out.println("处理完毕");
    printwriter.print("the size of "+filename+" is "+filesize);
  }
}

3.web.xml配置

  <servlet>
    <servlet-name>upload</servlet-name>
    <servlet-class>com.learn.servletupload</servlet-class>
    <init-param>
      <param-name>filepath</param-name>
      <param-value>file</param-value>
    </init-param>
    <init-param>
      <param-name>tempfilepath</param-name>
      <param-value>temp</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>upload</servlet-name>
    <url-pattern>/upload</url-pattern>
  </servlet-mapping>

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网