package com.CUST.brain.common.utils;

import com.CUST.brain.common.config.OssProperties;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class OssUtil {

    @Autowired
    private OssProperties ossProperties;

    public String upload(MultipartFile file, String objectName) {
        OSS ossClient = new OSSClientBuilder().build(
                ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret()
        );
        try {
            ossClient.putObject(ossProperties.getBucketName(), objectName, file.getInputStream());
            // 拼接文件公网访问地址
            return "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint().replace("https://", "") + "/" + objectName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            ossClient.shutdown();
        }
    }
} 