apache fileupload 文件上传,及文件进度设置获取
2024-10-16 04:07:52
文件上传action处理:
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(2048);
// 设置临时文件路径,通过设置临时文件可以在上传大文件时候达到多少先写入临时文件,不会造成卡死情况
String tempPath = "/mnt/disk1/tomcat/tomcat1/upload/tmp/";
File tempFile = new File(tempPath);
if (!tempFile.exists())
tempFile.mkdirs();
factory.setRepository(tempFile);
ServletFileUpload upload = new ServletFileUpload(factory);
//设置可上传文件大小
upload.setSizeMax(1024000000);
//设置文件进度监听器
UploadProgressListener progressListener = new UploadProgressListener();
//放入session中,下次访问可以取出,获取文件进度
session.setAttribute("progress", progressListener);
upload.setProgressListener(progressListener);
List<FileItem> fileldItems = null;
try {
fileldItems = upload.parseRequest(request);
} catch (FileUploadException e1) {
e1.printStackTrace();
}
Map<String, String> fieldMap = new HashMap<String, String>();
List<FileItem> fileList = new ArrayList<FileItem>();
Iterator<FileItem> iter = fileldItems.iterator();
StringBuffer url = new StringBuffer("request=");
url.append(request.getRequestURI());
while (iter.hasNext()) {
FileItem item = iter.next();
//获取非文件字段
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
url.append("&" + name + "=" + value);
fieldMap.put(name, value);
} else {
fileList.add(item);
}
}
//记录非文件字段
logger.error(url.toString().replaceFirst("&", "?"));
for (FileItem item : fileList) {
String fileName = item.getName();
if (fileName == null || fileName.equals(""))
continue;
fileName = fileName
.substring(fileName.lastIndexOf("\\") + 1);
String ext = fileName.substring(fileName.lastIndexOf("."));
fileName = fileName.substring(0, fileName.lastIndexOf("."));
String dateStr = DateUtil.formatDate(new Date(),
"yyyyMMddHHmmss");
String filename = fileName + "_" + dateStr + ext;
String filePath = "";
filePath = "/mnt/disk1/tomcat/tomcat1/upload/files/"
+ DecoderUtil.toChinese(fieldMap.get("user"));
File fp = new File(filePath);
if (!fp.exists())
fp.mkdirs();
File uploadedFile = new File(fp, filename);
try {
item.write(uploadedFile);
} catch (Exception e) {
e.printStackTrace();
}
}
ProgressListener:由于我这个不只记录了文件进度,还有别的信息,懒得删了,就这样黏上来了,可以根据情况自己修改。
package lbi.flow.util; import java.text.DecimalFormat; import org.apache.commons.fileupload.ProgressListener; public class UploadProgressListener implements ProgressListener {
private long megaBytes = -1;
private long readBytes = 0;
private long totalBytes = 0;
private long processedCount = 0;
private long totalCount = 0;
private String speed = "0";// k/s
private long starttime;
private int step = 1; private final DecimalFormat df = new DecimalFormat("0.##%");
private final DecimalFormat df2 = new DecimalFormat("0.##"); public UploadProgressListener() {
this.starttime = (long) System.currentTimeMillis();
} public String getProgress() {
if (this.step == 1)
return df.format(this.readBytes * 1.0 / this.totalBytes);
else
return df.format(this.processedCount * 1.0 / this.totalCount);
} public String getOverallProgress() {
if (this.step == 1)
return df.format(this.readBytes * 1.0 / this.totalBytes / 3);
else
return df.format(this.processedCount * 1.0 / this.totalCount / 3
+ (this.step - 1) * 1.0 / 3);
} public void update(long pBytesRead, long pContentLength, int pItems) {
long mBytes = pBytesRead / 1000000;
if (megaBytes == mBytes && pBytesRead != pContentLength) {
return;
}
megaBytes = mBytes;
long deadline = System.currentTimeMillis();
speed = df2.format(pBytesRead / 1024
/ ((deadline - starttime) * 1.0 / 1000));
readBytes = pBytesRead;
totalBytes = pContentLength;
} public long getProcessedCount() {
return processedCount;
} public void setProcessedCount(long processedCount) {
this.processedCount = processedCount;
} public long getTotalCount() {
return totalCount;
} public void setTotalCount(long totalCount) {
this.totalCount = totalCount;
} public int getStep() {
return step;
} public void setStep(int step) {
this.step = step;
} public String getSpeed() {
return this.speed;
}
}
这样,再写一个接口,通过session获取存储的ProgressListener即可获取上传文件的进度,可以支持多文件上传的。
最新文章
- ActionBar详解
- udacity google deep learning 学习笔记
- java实现远程储存读取文件
- asp.net 加载xml到menu
- rails创建项目,部署,测试流程(rails5.0+ruby2.3.1)
- POJ 3352 Road Construction(边双连通分量,桥,tarjan)
- lex/flex 笔记
- 如何快速正确的安装 Ruby, Rails 运行环境-b
- Piotr&#39;s Ants UVa 10881
- Django学习(六) 模板
- web.config中<;customErrors>;节点
- which 查看可执行文件的位置
- java 生产者 与 消费者的案例
- UltraEdit MAC破解方法
- CryptoTools加密与解密
- JS输出26个英文大小写字母
- sql中count(*)、count(col)、count(1)区别
- Reachability实时监控网络变化
- MongoDB副本集(一主一备+仲裁)环境部署-运维操作记录
- 基于 Spring Cloud 完整的微服务架构实战
热门文章
- Jqgrid pager 关于“local” dataType 动态加载数据分页的研究(没好用的研究结果)
- css3: 基本知识记录
- mysql同步复制异常的常见操作-传统复制方式
- sklearn—特征工程
- FastDFS + Nginx代理方式访问
- CrawlSpiders模块的使用
- Git(使用码云)
- `&;nbsp;` `&;emsp;` `&;ensp;` `&;thinsp;`
- 如何计算UDP/TCP检验和checksum
- js 图片压缩上传(纯js的质量压缩,非长宽压缩)