FileUpload控件使用

使用组件的关联JAR包:

commons-fileupload-1.2.2.jar

commons-io-2.4.jar

使用方式:

创建磁盘工厂

DiskFileItemFactory factory = new DiskFileItemFactory();

 

设置文件缓存路径

File temp = new File(this.getServletContext().getRealPath(“/”) + “temp”) ;

factory.setReponsitory(temp) ;

 

创建处理工具

ServletFileUpload upload = new ServletFileUpload();

 

设置上传文件大小的上限,-1表示无限

upload.setSizeMax(3 * 1024 * 1024)  ;             //最大上传大小为3M

上传文件,并解析出所有的表单字段,包括普通字段和文件字段

接受所有的内容,以List形式存储在系统缓存中

List<FileItem> all  =  upload.praseRequest(request)  ;

Iterator<FileItem> iter  =  all.iterator()  ;

遍历取得

while(iter.hasNext()){

FileItem item =iter.next()  ;

String fieldName =item.getFieldName()  ;       //取得控件名称

if(!item.isFormField()){              //判断是否是普通文本

    String name = item.getName()  ;     //取得文件名称

    String contentType =item.getContentType()  ;      //取得文本类型

    long size =item.getSize()  ;       //取得文件大小

    File saveFile = null ;

    InputStream input = null ;        //输入流

    OutputStream output = null ;       //输出流

//取得随机名

    IpTiemStamp its = newIpTimeStamp(request.getRemoteAddr()) ;

    input = item.getInputStream() ;       //取得缓存中的数据

    //设置文件保存路径

    saveFile = new File( this.getServletContext().getRealPath(“/”)

             + ”upload” + File.separator+ its.getIpTimeRand() 

             + ”.” + item.getName().split(“.”)[1]);

    output = new FileOutputStream(saveFile) ;

    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()  ;     //取得表单传递的值

}

}

使用情况

FileUpload控件一般使用在框架中,否则一般使用smartUpload控件完成上传功能。因为前者的使用非常复杂繁琐。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值