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

com.yanyun.cloud.OSSClient Maven / Gradle / Ivy

There is a newer version: 1.0.8
Show newest version
package com.yanyun.cloud;

import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Service
public class OSSClient {

    private String url = System.getenv("oss.url");
    private String accessKey = System.getenv("oss.accessKey");
    private String secretKey = System.getenv("oss.secretKey");
    private String bucketName = System.getenv("oss.bucketName");
    private String downloadUrl = null;

    @Resource
    private Environment env;

    private MinioClient minioClient = null;

    @PostConstruct
    public void init() throws Exception {
        url = url == null ? env.getProperty("oss.url") : url;
        accessKey = accessKey == null ? env.getProperty("oss.accessKey") : accessKey;
        secretKey = secretKey == null ? env.getProperty("oss.secretKey") : secretKey;
        bucketName = bucketName == null ? env.getProperty("oss.bucketName") : bucketName;
        if ((url == null) || (accessKey == null) || (secretKey == null) || (bucketName == null)) {
            System.out.println("OSS未初始化:需要oss.");
        } else {
            try {
                minioClient = new MinioClient(url, accessKey, secretKey);
                if (!minioClient.bucketExists(bucketName)) {
                    minioClient.makeBucket(bucketName);
                }

                downloadUrl = url + "/download/" + bucketName + "/";
                System.out.println("OSS初始化成功");
            } catch (Exception e) {
                throw new Exception("OSS初始化失败:" + e.getMessage());
            }
        }
    }

    private String exName(MultipartFile multipartFile) {
        try {
            String[] fileNames = multipartFile.getOriginalFilename().split("\\.");
            if (fileNames.length > 1) {
                return "." + fileNames[fileNames.length - 1];
            }
        } catch (Exception e) {

        }

        return "";
    }

    public String save(MultipartFile multipartFile) throws Exception {
        try {
            String objectName = SnowFlakeIdGenerator.generateString() + exName(multipartFile);
            PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), -1);

            minioClient.putObject(bucketName, objectName, multipartFile.getInputStream(), putObjectOptions);

            return downloadUrl + objectName;
        } catch (Exception e) {
            throw new Exception("OSS异常:" + e.getMessage());
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy