The uploading progress listener. Its progressChanged API is called by the SDK when there's an update.br/>*/
@Component
static class PutObjectProgressListener implements ProgressListener {
private long bytesWritten = 0;
private long totalBytes = -1;
private boolean succeed = false;
//private int percent = 0;br/>@Autowired
private RedisUtil redisUtil;
//上传进度的ID,作为 redis key 值
private String uploadId ="";
//构造方法中加入session
public PutObjectProgressListener() {
}
public PutObjectProgressListener(RedisUtil redisUtil,String uploadId) {
this.redisUtil=redisUtil;
this.uploadId=uploadId;
}
@Override
public void progressChanged(ProgressEvent progressEvent) {
long bytes = progressEvent.getBytes();
ProgressEventType eventType = progressEvent.getEventType();
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;
if (this.totalBytes != -1) {
int percent = (int)(this.bytesWritten * 100.0 / this.totalBytes);
try {
Map<String,Object> recordMap=new HashMap<>();
recordMap.put("progress",percent);
recordMap.put("bytesWritten",this.bytesWritten);
recordMap.put("totalBytes",this.totalBytes);
// 1小时后过期时间
long endTime =new Date(new Date().getTime() + 3600 * 1000).getTime();
// 当前时间
long nowTime = new Date().getTime();
long times = endTime - nowTime;
String uploadRecord=JasonUtil.mapToJson(recordMap);
logger.info("uploadRecord>>>>>>>>:"+uploadRecord);
String redisKey = Constants.MSG_UPLOAD_RECORD_REDIS_KEY_PREFIX+this.uploadId;
redisUtil.set(redisKey,uploadRecord, times, TimeUnit.MILLISECONDS);
logger.info(bytes + " bytes have been written at this time, upload progress: " +
percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
} catch (IOException e) {
e.printStackTrace();
}
} else {
logger.info(bytes + " bytes have been written at this time, upload ratio: unknown" +
"(" + this.bytesWritten + "/...)");
}
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:
System.out.println("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
break;
default:
break;
}
}
public boolean isSucceed() {
return succeed;
}
}
Ctrl+Enter 发布
发布
取消