当前位置: 移动技术网 > IT编程>开发语言>Java > java组件SmartUpload和FileUpload实现文件上传功能

java组件SmartUpload和FileUpload实现文件上传功能

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

本文为大家分享了java组件实现文件上传功能的具体代码,供大家参考,具体内容如下

1 smartupload上传组件

smartupload上传组件包,可以轻松的实现文件的上传和下载功能;

使用简单,实现上传文件类型的限制,也可以轻易的取得上传文件的名称、后缀、大小等;

smartupload本身是系统提供的jar包,将此包考入到lib文件夹中;

此组件的提供方网站已关闭,smartupload在非框架中开发中较为好用;

上传单个文件

要进行上传,必须使用html中提供给的file空间,而且<form>必须使用enctype属性进行封装;

smartupload_demo01.html : 上传表单

<html>
<head><title>上传表单</title></head>
<body>
<form action="smartupload_demo01.jsp" method="post" enctype="multipart/form-data">
  请选择要上传的文件:<input type="file" name="pic">
  <input type="submit" value="上传">
</form>
</body>
</html>

在form上使用enctype进行了表单封装,表示表单将按二进制的方式提交,即所有的表单此时不在是分别提交,而是将所有的内容都按照二进制的方式提交;

smartupload_demo01.jsp : 接收图片,保存在根目录中的upload文件夹中

<%@ page contenttype="text/html" pageencoding="gbk"%>
<%@ page import="org.bug.smart.*"%>
<html>
<head><title>接收图片,保存在根目录中的upload文件夹中</title></head>
<body>
<%
  smartupload smart = new smartupload() ;
  smart.initialize(pagecontext) ;  // 初始化上传操作
  smart.upload() ;      // 上传准备
  smart.save("upload") ;  // 文件保存
%>
</body>
</html>

使用smartupload时必须严格按照如上程序进行,最后在保存时只是写了一个upload,表示上传文件的保存文件夹,此文件要在根目录中手工建立;

保存的名称和上传的文件一样,所以如果出现相同的文件名称,将出现覆盖的情况;

混合表单

当一个表单使用了enctyoe封装后,其它文件类的表单控件的内容将无法通过request内置对象取得;

此时,必须通过smartupload类中提供的getrequest()方法取得全部的请求参数;

smartupload_demo02.html ; 混合表单

<html>
<head><title>混合表单</title></head>
<body>
<form action="smartupload_demo02.jsp" method="post" enctype="multipart/form-data">
  姓名:<input type="text" name="uname"><br>
  照片:<input type="file" name="pic"><br>
  <input type="submit" value="上传">
  <input type="reset" value="重置">
</form>
</body>
</html>

以上表单中包含了文本和文件两个控件;

smartupload_demo02.jsp : 接收封装表单的文本数据

<%@ page contenttype="text/html" pageencoding="gbk"%>
<%@ page import="org.bug.smart.*"%>
<%@ page import="cn.com.bug.util.*"%>
<html>
<head><title>接收封装表单的文本数据</title></head>
<body>
<%
  request.setcharacterencoding("gbk") ;
%>
<%
  smartupload smart = new smartupload() ;
  smart.initialize(pagecontext) ;  // 初始化上传操作
  smart.upload() ;      // 上传准备
  string name = smart.getrequest().getparameter("uname") ;
  smart.upload("upload");%>
<h2>姓名:<%=name%></h2>
<h2>request无法取得 : <%=request.getparameter("uname")%> </h2>
</body>
</html>

表单进行了二进制封装,单靠request对象是无法取得提交参数的,必须依靠smartupload类中的getrequest().getparameter()方法才能取得请求的参数;

由于是通过smartupload完成参数接收,所以smart.getrequest()方法一定要在执行完upload()方法后才可使用;

为上传文件自动命名

为了解决文件名称相同而出现覆盖的情况,可以采用为上传文件自动命名的方式;

自动命名可采用格式: ip地址+时间戳+三位随机数

iptimestamp.java : 定义取得ip时间戳的操作类

package cn.com.bug.util ;
import java.text.simpledateformat ;
import java.util.date ;
import java.util.random ;
public class iptimestamp {
  private simpledateformat sdf = null ; //定义simpledateformat对象
  private string ip = null ; //接收ip地址
  public iptimestamp(){
  }
  public iptimestamp(string ip){ //得到ip地址+时间戳+三位随机数
    this.ip = ip ;
  }
  public string getiptimerand(){
    stringbuffer buf = new stringbuffer() ; //实例化stringbuffer对象
    if(this.ip != null){
      string s[] = this.ip.split("\\.") ; //进行拆分操作
      for(int i=0;i<s.length;i++){ //循环设置ip地址
        buf.append(this.addzero(s[i],3)) ; //不够三位要补0
      }
    }
    buf.append(this.gettimestamp()) ; //取得时间戳
    random r = new random() ; //定义random对象,已产生随机数
    for(int i=0;i<3;i++){ //循环三次
      buf.append(r.nextint(10)) ; //增加随机数
    }
    return buf.tostring()  //返回名称
  }
  public string getdate(){ //取得当前系统的时间
    this.sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss.sss") ;
    return this.sdf.format(new date()) ;
  }
  public string gettimestamp(){ //取得时间戳
    this.sdf = new simpledateformat("yyyymmddhhmmsssss") ;
    return this.sdf.format(new date()) ;
  }
  private string addzero(string str,int len){ //补0操作
    stringbuffer s = new stringbuffer() ;
    s.append(str) ;
    while(s.length() < len){
      s.insert(0,"0") ;
    }
    return s.tostring() ;
  }
  public static void main(string args[]){
    system.out.println(new iptimestamp("192.168.1.1").getiptimerand()) ;
  }
}

直接修改上传的操作页,在上传的操作页中不直接使用save()方法保存;

而是取得一个具体上传文件对象才可以保存,由于上传文件时文件的后缀需要统一,所以可以使用getfileext()方法取得文件的后缀;

smartupload_demo02.jsp : 增加自动命名的功能;

<%@ page contenttype="text/html" pageencoding="gbk"%>
<%@ page import="org.bug.smart.*"%>
<%@ page import="cn.com.bug.util.*"%>
<html>
<head><title>修改后的smartuoload.jsp</title></head>
<body>
<%
  request.setcharacterencoding("gbk") ;
%>
<%
  smartupload smart = new smartupload() ;
  smart.initialize(pagecontext) ;  // 初始化上传操作
  smart.upload() ;      // 上传准备
  string name = smart.getrequest().getparameter("uname") ;
  iptimestamp its = new iptimestamp(request.getremoteaddr()) ;  // 取得客户端的ip地址
  string ext = smart.getfiles().getfile(0).getfileext() ;  // 扩展名称
  string filename = its.getiptimerand() + "." + ext ;
  smart.getfiles().getfile(0).saveas(this.getservletcontext().getrealpath("/")+"upload"+java.io.file.separator + filename) ;
%>
<%=smart.getfiles().getfile(0).getfilename().matches("^\\w+.(jpg|gif)$")%>
<h2>姓名:<%=name%></h2>
<img src="../upload/<%=filename%>">
</body>
</html>

由于smartupload可以同时接收多个文件;

此时通过smart.getfiles().getfile(0).getfileext()取得第一个上传文件的文件后缀,在与之前iptimestampl类生成的文件名称一起拼凑出一个新的文件名;

此时要用的新的文件名称保存上传文件,所以要通过smart.getfiles().getfile(0).saveas()方法进行收工保存;

以上代码没有对上传文件的类型进行限制,可以通过正则判断文件的后缀是否合法;

eg:验证上传文件的合法性代码片段

if(smart.getfiles().getfile(0).getfilename().matches("^\\w+\\.(jsp|gif)$")){
    //表示只允许后缀为jpg或gif的文件上传;
}

批量上传

  smart.getfiles().getfile(0).saveas(this.getservletcontext().getrealpath("/")+"upload"+java.io.file.separator + filename) ;
以上证明可以一次性提交多个上传文件;

smartupload_demo03.jsp : 编写表单,上传3个文件

<html>
<head><title>编写表单,上传3个文件</title></head>
<body>
<form action="smartupload_demo03.jsp" method="post" enctype="multipart/form-data">
  照片1:<input type="file" name="pic1"><br>
  照片2:<input type="file" name="pic2"><br>
  照片3:<input type="file" name="pic3"><br>
  <input type="submit" value="上传">
  <input type="reset" value="重置">
</form>
</body>
</html>

如果要完成批量上传,则肯定要使用循环的方式进行,必须通过以下方式取得上传文件数量;

取得上传文件的数量:smart.getfiles().getcount();

smartupload_demo03.jsp : 批量上传

<%@ page contenttype="text/html" pageencoding="gbk"%>
<%@ page import="org.bug.smart.*"%>
<%@ page import="cn.com.bug.util.*"%>
<html>
<head><title>批量上传</title></head>
<body>
<%
  request.setcharacterencoding("gbk") ;
%>
<%
  smartupload smart = new smartupload() ;
  smart.initialize(pagecontext) ;  // 初始化上传操作
  smart.upload() ;      // 上传准备
  string name = smart.getrequest().getparameter("uname") ;
  iptimestamp its = new iptimestamp(request.getremoteaddr()) ;  // 取得客户端的ip地址
  for(int x=0;x<smart.getfiles().getcount();x++){
    string ext = smart.getfiles().getfile(x).getfileext() ;  // 扩展名称
    string filename = its.getiptimerand() + "." + ext ;
    smart.getfiles().getfile(x).saveas(this.getservletcontext().getrealpath("/")+"upload"+java.io.file.separator + filename) ;
  }
%>
</body>
</html>

2 fileupload

fileupload是apache组织提供的免费上传组件,可以直接从站点进行下载();

fileupload组件本身依赖于commons组件包,所以从apache下载此组件的同时连同commons组件的io包一起下载();

commons组件包在很多框架开发中都可以直接使用,此包中提供了大量开发类可作为java的有力补充;

将commons-fileupload-1.2.1.jar和common-io-1.4.jar配置到lib文件夹中;

使用fileupload接收上传内容

不论是使用smartupload和fileupload进行上传操作,都是依靠html的file控件完成的;

fileupload_demo01.html : 上传表单

<html>
<head><title>上传表单</title></head>
<body>
<form action="fileupload_demo01.jsp" method="post" enctype="multipart/form-data"> 
  姓名:<input type="text" name="uname"><br>
  照片:<input type="file" name="pic"><br>
  <input type="submit" value="上传">
  <input type="reset" value="重置">
</form>
</body>
</html>

fileupload的具体上传操作与smartupload相比有着很高的复杂度;

以下是fileupload上传的步骤:

   1 创建磁盘工厂:diskfileitemfactory factory = new diskfilefactory();

   2 创建处理工具:servletfileupload upload =new servletfileupload(factory);

   3 设置文件的上传大小:upload.setfilesizemax(3145728);

   4 接收全部的内容:list<fileitem> items = upload.parserequest(request);

fileupload对所有的上传内容都采用同样的方式操作;

与smartupload不同的是,会将所有的上传内容一起(包括文件和普通参数)接收;

所以需要依次判断你每一次上传的内容是文件还是普通文本;

fileupload_demo01.jsp : 接收上传文件

<%@ page contenttype="text/html" pageencoding="gbk"%>
<%@ page import="java.util.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<html>
<head><title>接收上传文件</title></head>
<body>
<%
  diskfileitemfactory factory = new diskfileitemfactory() ;
  servletfileupload upload = new servletfileupload(factory) ;
  upload.setfilesizemax(3 * 1024 * 1024) ;  // 只能上传3m
  list<fileitem> items = upload.parserequest(request) ; // 接收全部内容
  iterator<fileitem> iter = items.iterator() ;//将全部的内容变为iterator实例
  while(iter.hasnext()){ //依次取出每一个内容
    fileitem item = iter.next() ; //取出每一个上传的文件
    string fieldname = item.getfieldname() ;  // 取得表单控件的名称
%>
    <ul><h4><%=fieldname%> --> <%=item.isformfield()%></h4>
<%
    if(!item.isformfield()){    // 不是普通文本
      string filename = item.getname() ;  // 取得文件的名称
      string contenttype = item.getcontenttype() ;  // 文件类型
      long sizeinbytes = item.getsize() ;//文件大小
%>
      <li>上传文件名称:<%=filename%>
      <li>上传文件类型:<%=contenttype%>
      <li>上传文件大小:<%=sizeinbytes%>
<%
    } else {
      string value = item.getstring() ;
%>
      <li>普通参数:<%=value%>
<%
    }
%>    </ul>
<%
  }
%>
</body>
</html>

fileupload组件接收完全部的数据后,所有的数据都保存在list集合中,则需要使用iterator取出每一个数据;

但是由于其中既有普通的文本数据又有上传的文件,每一个上传内容都使用一个fileitem类对象表示;

所以当使用iterator依次取出每一个fileitem对象时,就可以使用fileitem类中的isformfield()方法来判断当前操作的内容是普通的文本还是附件上传;

如果是上传文件,则将文件的内容依次取出;如果是普通的文本,则直接通过getstring()方法取得具体的信息;

保存上传内容

以上完成了接收上传文件内容的操作,但是所上传的文件现在并没有真正的保存在服务器上;

而要进行文件的保存,在fileupload中就必须通过java.io包中inputstream和outputstream两个类完成文件的自动命名操作;

inputstream和outputstream为两个抽象类,必须依靠fileinputstream和outputstream类进行对象的实例化操作;

fileupload_demo02.html : 定义上传表单,可以同时上传多个文件

<html>
<head><title>定义表单,可以同时上传多个文件</title></head>
<body>
<form action="fileupload_demo02.jsp" method="post" enctype="multipart/form-data"> 
  姓名:<input type="text" name="uname"><br>
  照片:<input type="file" name="pic1"><br>
  照片:<input type="file" name="pic2"><br>
  照片:<input type="file" name="pic3"><br>
  <input type="submit" value="上传">
  <input type="reset" value="重置">
</form>
</body>
</html>

fileupload_demo02.jsp : 保存上传的内容

<%@ page contenttype="text/html" pageencoding="gbk"%>
<%@ page import="java.util.*,java.io.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="cn.com.bug.util.*"%>
<html>
<head><title>保存上传内容</title></head>
<body>
<%
  diskfileitemfactory factory = new diskfileitemfactory() ;
  factory.setrepository(new file(this.getservletcontext().getrealpath("/") + "uploadtemp")) ;    // 设置一个临时文件
  servletfileupload upload = new servletfileupload(factory) ;
  upload.setfilesizemax(3 * 1024 * 1024) ;  // 只能上传3m
  list<fileitem> items = upload.parserequest(request) ; // 接收全部内容
  iterator<fileitem> iter = items.iterator() ; //将全部的内容转换为iterator实例
  iptimestamp its = new iptimestamp(request.getremoteaddr()) ;//实例化ip时间戳对象
  while(iter.hasnext()){//依次取出每一个内容
    fileitem item = iter.next() ; //取出每一个上传的文件
    string fieldname = item.getfieldname() ;  // 取得表单控件的名称
%>
    <ul><h4><%=fieldname%> --> <%=item.isformfield()%></h4>
<%
    if(!item.isformfield()){    // 不是普通文本,是上传文件
      file savefile = null ;   //定义保存的文件
      inputstream input = null ;
      outputstream output = null ;
      input = item.getinputstream() ;
      output = new fileoutputstream(new file(this.getservletcontext().getrealpath("/")+"upload"+file.separator+its.getiptimerand()+
               "."+item.getname().split("\\.")[1])) ;//定义输入文件的路径
      int temp = 0 ;
      byte data[] = new byte[512] ;
      while((temp=input.read(data,0,512))!=-1){ //依次读取内容
        output.write(data) ;  // 分块保存
      }
      input.close() ;
      output.close() ;
    } else {
      string value = item.getstring() ;//取出表单的内容
%>
      <li>普通参数:<%=value%>
<%
    }
%>    </ul>
<%
  }
%>
</body>
</html>

以上代码中,首先会将所有的上传文件设置到临时文件夹中;

如果发现取得的表单是上传文件,则使用inputstream,从fileitem类中取得文件的输入流;

在使用outputstream将内容依次取出,保存在具体的文件路径中; 

fileupload在建的不便之处:

1 无法像使用request.getparameter()方法那样准确地取得提交的参数;

2 无法像使用request.getparametervalues()那样准确的取得一组提交参数;

3 所有的上传文件度需要进行一次的判断,才能够分别保存,不能一次性批量保存;

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

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

相关文章:

验证码:
移动技术网