怎么用多线程实现进度条同步上传
爱上走路 2013-02-13 11:28:10 DiskFileItemFactory factory = new DiskFileItemFactory();//磁盘缓存
ServletFileUpload upload = new ServletFileUpload(factory);//创建一个文件上传处理器
upload.setFileSizeMax(5 * 1024 * 1024 * 1024);
//监听文件上传进度,可在控制台打印进度
upload.setProgressListener(new ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, int items) {
String all = bytesRead + "";
double d = Double.parseDouble(all);
System.out.println("当前文件是大小是:" + contentLength / 1024 + "KB,已上传" + bytesRead / 1024 + "KB,当前已上传:" + (int) (d / contentLength * 100) + "%");
}
});
InputStream stream = null;
FileOutputStream writer = null;
try {
//上传文件,并解析出所有的表单字段,包括普通字段和文件字段
List<FileItem> itemList = upload.parseRequest(request);
for (FileItem item : itemList) {//遍历表单字段
if (!item.isFormField()) {//如果不是普通的表单字段
//首先将文件上传到服务器
String name = item.getName();
stream = item.getInputStream();
if (!checkExcel(stream)) {//判断上传的excel的表头是否正确
return;
}
String path = this.getServletContext().getRealPath("");
File filepath = new File(path.replaceAll("build", "") + "/WEB-INF/anjuexcel");
if (!filepath.exists()) {
filepath.mkdir();//如果没有文件夹创建一个新的文件夹
}
if (name.contains("\\")) {
name = name.substring(name.lastIndexOf("\\"));//去掉完整路径,只保留文件名
}//注意IE或FireFox中获取的文件名是不一样的,IE中是绝对路径,FireFox中只是文件名。
realpath = path + name;
File file = new File(realpath);
if (!file.exists()) {
file.createNewFile();//创建新的文件
}
writer = new FileOutputStream(file);
int data;
data = stream.read();
while (data != -1) {
writer.write(data);
data = stream.read();
}
writer.close();
stream.close();
}
}
} catch (Exception ex) {
Logger.getLogger(ImpotBzsfwhsxxAction.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (writer != null) {
writer.close();
}
if (stream != null) {
stream.close();
}
}
我这里没有写线程,求指点