Common file upload组件的使用

本文介绍了一种在JSP环境中使用Apache Commons FileUpload组件进行文件上传的方法。通过具体实例展示了如何解析请求并处理上传文件,包括设置上传配置、解析文件项及处理过程中的注意事项。
Spring, Myface, tomcat manager上传一般都是使用这个上传包, 但是他们继续高层封装了更方便的接口UploadFile和MultipleRequest等, 用起来比较傻瓜. 但是有时直接在JSP用request来处理上传, 就需要老实的使用common upload的API了.


<FORM name=uploadForm action=upload.jsp method=post encType='multipart/form-data'>
Please select one file to upload:
<INPUT type=file size=100 name=uploadFile> <input type=submit name=uploadButton value='Start upload' onClick="displayLoadingBar('Uploading file, please wait...')">
</FORM>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.DiskFileUpload"%>
String currentPath = (String) session.getAttribute("currentPath");
//NOTICE, 还有其他FileUpload的实现, 在新的fileupload包中. 很久以前写的代码下面很乱,不如直接看apache common upload带的例子 :-)
DiskFileUpload upload 
= new DiskFileUpload();
   //应该还有个file thread hole
   //这个是buffer size?
upload.setSizeMax(
-1);
   //保存的临时路径?
upload.setRepositoryPath(currentPath);

   //这步应该不会保存上传文件为临时文件吧? 应该只是列表, 适合的FileItem可以获取到content type
  //大小. 
List items 
= upload.parseRequest(request);
Iterator iter 
= items.iterator();
//We only allow to upload one file right now.
final String UPLOAD_FILE_FIELD = "uploadFile";
FileItem uploadFileItem 
= null;
while (iter.hasNext()) {
    FileItem item 
= (FileItem) iter.next();
    
//System.out.println("fieldName=" + item.getFieldName() + ",isFormField=" + item.isFormField());
    if (!item.isFormField() && UPLOAD_FILE_FIELD.equals(item.getFieldName()) && uploadFileItem == null{
        uploadFileItem 
= item;
    }
        //剩下的这些应该就是form的field, 例如input type=text和其他传过来的参数.
    else {
        item.delete();
    }

}

if (uploadFileItem == null{
    out.print(
"<font color=red>Upload failed.</font>");
    
return;
}

   //FileItem有个write的方法, 估计是又生成一个文件了, 拷贝临时文件, 如果是同一个分区, rename应该是快些的。 如果上传的文件下也没所谓了.
    public boolean write(File targetFile) {
        try {
            fileItem.write(targetFile);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值