All Downloads are FREE. Search and download functionalities are using the official Maven repository.

plus.easydo.starter.file.service.CommonFileStoreServer Maven / Gradle / Ivy

The newest version!
package plus.easydo.starter.file.service;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import plus.easydo.core.result.DataResult;
import plus.easydo.core.result.R;
import plus.easydo.starter.file.FileResult;
import plus.easydo.starter.file.FileStoreObject;
import plus.easydo.starter.file.minio.MinioFileResult;
import plus.easydo.starter.file.exception.FileStoreException;

import java.math.BigDecimal;
import java.util.Objects;


/**
 * 文件存储服务的抽象实现类,实现共有方法
 * @author laoyu
 * @version 1.0
 */
public abstract class CommonFileStoreServer extends DataResult implements FileStoreService{

    private static final String FILE_PATH_END_WITH = "/";

    protected FileStoreObject fileStoreObject;
    protected INPUT_FILE file;
    protected String filePath;
    protected String fileName;
    protected String groupName;
    protected BigDecimal fileKbSize;

    @Autowired
    protected TEMPLATE template;

    @Override
    public TEMPLATE getTemplate() {
        return this.template;
    }

    @Override
    public R save(FileStoreObject fileStoreObject) {
        validationFile(fileStoreObject.getFile());
        this.fileStoreObject = fileStoreObject;
        this.file = fileStoreObject.getFile();
        this.fileName = buildFileName(fileStoreObject.getFile(),fileStoreObject.getFileName());
        this.filePath = buildFilePath(fileStoreObject.getFilePath());
        this.groupName = buildGroupName(fileStoreObject.getGroupName());
        this.fileKbSize = getFileKbSize(file);
        return ok(buildResult());
    }

    @Override
    public void validationFile(INPUT_FILE inputFile) {
        if(Objects.isNull(inputFile)){
            throw new FileStoreException("file is empty");
        }
    }

    @Override
    public String buildFilePath(String filePath) {
        if (StrUtil.isBlank(filePath)){
            filePath = LocalDateTimeUtil.format(LocalDateTimeUtil.now(), DatePattern.PURE_DATE_PATTERN) + FILE_PATH_END_WITH;
        }else if (filePath.endsWith(FILE_PATH_END_WITH)){
            filePath = filePath + FILE_PATH_END_WITH;
        }
        return filePath;
    }

    @Override
    public FileResult buildResult() {
        MinioFileResult result = new MinioFileResult();
        result.setGroupName(groupName);
        result.setFileName(fileName);
        result.setFilePath(filePath);
        result.setFileSize(fileKbSize);
        return result;
    }
}