UploadPartRequestFactory.java 2.27 KB
package com.cnlive.cnUploadDemo.utils;

import com.cnlive.libs.upload.services.CNUploadPartRequest;

import java.io.File;
import java.io.Serializable;

/**
 * UploadPartRequest工厂,用于分块上传操作
 */
public class UploadPartRequestFactory implements Serializable {

    private static final long serialVersionUID = 1L;
    /**
     * 指定的Object键
     */
    private String key;

    /**
     * 初始化时得到的uploadId
     */
    private String uploadId;

    /**
     * 需要上传的file
     */
    private File file;

    /**
     * 此分块是第几块
     */
    public int partNumber = 1;

    /**
     * 此分块在文件中内容的起始位置
     */
    private long offset = 0L;

    /**
     * 剩余大小
     */
    private long remainingBytes;

    /**
     * 此分块的大小,单位为Byte
     */
    public long partSize;

    /**
     * 已经上传大小
     */
    private long uploadedSize;

    public UploadPartRequestFactory(String objectKey, String uploadId, File file, long partSize) {
        this.uploadId = uploadId;
        this.key = objectKey;
        this.file = file;
        this.remainingBytes = file.length();
        this.partSize = partSize;
        this.partNumber = 1;
        this.uploadedSize = 0;
    }

    public synchronized boolean hasMoreRequests() {
        return this.remainingBytes > 0L;
    }

    // 计算下一个UploadPartRequest配置参数,并返回对象
    public synchronized CNUploadPartRequest getNextUploadPartRequest() {
        boolean bool = this.remainingBytes - this.partSize <= 0L;
        CNUploadPartRequest localUploadPartRequest = null;
        uploadedSize = file.length() - this.remainingBytes;

        localUploadPartRequest = new CNUploadPartRequest(key, uploadId, file, offset, partNumber++, partSize);

        this.offset += partSize;
        this.remainingBytes -= partSize;
        localUploadPartRequest.setLastPart(bool);
        return localUploadPartRequest;
    }


    public synchronized long getUploadedSize() {
        return this.uploadedSize;
    }

    public synchronized File getFile() {
        return this.file;
    }

    public synchronized String getUploadId() {
        return this.uploadId;
    }

    public synchronized String getObjectKey() {
        return this.key;
    }

}