技术开发 频道

DWR开发基于Ajax文件上载portlet


开始创建文件上载 portlet

   文件上载 portlet 的基石是 Apache Commons FileUpload 包(本文也称之为 FileUpload)。除了支持 servlet 内的文件上载外,Apache Commons FileUpload Version 1.1 包还支持 portlet 中的文件上载。本文使用的是 Apache Commons FileUpload 版本 1.2。 

   基本上,开发文件上载进度条需要两步:

   在服务器端检索文件上载过程

   从门户服务器进行客户端的文件上载检索和显示

   文件上载过程的服务器端检索

   FileUpload 包支持使用侦听器检索文件上载过程。在文件上载 portlet 的 doUpload() 方法(称为 uk.ac.dl.esc.gtg.myportlets.fileupload.FileUploadPortlet,包括在本文 下载 部分所提供的源文件中),通过调用 setProgressListener() 方法为 PortletFileUpload 设置过程侦听器,如 清单 1 所示:

   清单 1. 为文件上载包设置过程侦听器

DiskFileItemFactory factory = new DiskFileItemFactory(); 
PortletFileUpload pfu = new PortletFileUpload(factory);
pfu.setSizeMax(uploadMaxSize); // Maximum upload size
pfu.setProgressListener(new FileUploadProgressListener());
   侦听器 FileUploadProgressListener(参见 清单 2)可实现 org.apache.commons.fileupload.ProgressListener 接口。update() 方法自动由 FileUpload 包调用以刷新有关所传输字节数的最新信息。在本文的实现中,每传输 10KB 数据则更新一次进度。这有助于防止更新进行得太频繁。 getFileUploadStatus() 方法用来计算当前文件上载进度,可由客户机通过 DWR 调用(在下一节讨论)。

清单 2. 检索文件上载过程的文件上载侦听器
package uk.ac.dl.esc.gtg.myportlets.fileupload; 

import java.text.NumberFormat;

import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileUploadProgressListener implements ProgressListener {
private static Log log = LogFactory.getLog(FileUploadProgressListener.class);

private static long bytesTransferred = 0;

private static long fileSize = -100;

private long tenKBRead = -1;

public FileUploadProgressListener() {
}

public String getFileUploadStatus() {
// per looks like 0% - 100%, remove % before submission
String per = NumberFormat.getPercentInstance().format(
(double) bytesTransferred / (double) fileSize);
return per.substring(0, per.length() - 1);
}

public void update(long bytesRead, long contentLength, int items) {
// update bytesTransferred and fileSize (if required) every 10 KB is
// read
long tenKB = bytesRead / 10240;
if (tenKBRead == tenKB)
return;
tenKBRead = tenKB;

bytesTransferred = bytesRead;
if (fileSize != contentLength)
fileSize = contentLength;
}

}

0
相关文章