添加上传文件进度条

This commit is contained in:
wuchunlei
2024-03-13 14:44:35 +08:00
parent e6d1250cf6
commit cf2fa5daf6

View File

@@ -0,0 +1,54 @@
package com.peanut.modules.oss.controller;
import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import com.peanut.common.utils.SpringContextUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
public class PutObjectProgressListener implements ProgressListener {
private long bytesWritten = 0;
private long totalBytes = 0;
private String fileName = "";
public PutObjectProgressListener() {
}
public PutObjectProgressListener(long fileSize,String fileName) {
this.totalBytes = fileSize;
this.fileName = fileName;
}
@Override
public void progressChanged(ProgressEvent progressEvent) {
long bytes = progressEvent.getBytes();
ProgressEventType eventType = progressEvent.getEventType();
StringRedisTemplate redisTemplate = (StringRedisTemplate)SpringContextUtils.getBean("stringRedisTemplate");
switch (eventType) {
case TRANSFER_STARTED_EVENT:
// System.out.println("Start to upload......");
// break;
case REQUEST_CONTENT_LENGTH_EVENT:
//因为传的是文件流,不走此路
// this.totalBytes = bytes;
// System.out.println(this.totalBytes + " bytes in total will be uploaded to OSS");
// break;
case REQUEST_BYTE_TRANSFER_EVENT:
this.bytesWritten += bytes;
int percent = (int)(this.bytesWritten * 100.0 / this.totalBytes);
// System.out.println(bytes + " bytes have been written at this time, upload progress: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
redisTemplate.opsForValue().set(fileName,percent+"");
break;
case TRANSFER_COMPLETED_EVENT:
// this.succeed = true;
// System.out.println("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
// break;
case TRANSFER_FAILED_EVENT:
redisTemplate.delete(fileName);
// System.out.println("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
// break;
default:
break;
}
}
}