怎么用多线程实现进度条同步上传

爱上走路 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();
}
}
我这里没有写线程,求指点
...全文
218 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
yktd26 2013-02-14
  • 打赏
  • 举报
回复
这是客户端的事情啊,客户端如果并行上传,服务器端会收到并行请求,自然是多线程上传,不需要你服务端手动开线程,进度条是客户端根据总上传量来计算进度条,服务端只需要检测到最后一个chunk而合并文件
a12939026 2013-02-13
  • 打赏
  • 举报
回复
不是让Servlet实现runnable接口做的。。 可以参看下面的文章。 http://www.cnblogs.com/xiaoao808/archive/2009/08/03/1537870.html
爱上走路 2013-02-13
  • 打赏
  • 举报
回复
如果我让Servlet类继承Runnable接口,run方法应该怎么写,才能让程序实现上传文件并且同时控制前段界面进度条的同步显示?需要指点

81,094

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧