从阿里OSS下载照片并转base64返回

package bj.ca.test.test00.test.vo;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

@Slf4j
@Service
public class AliOssUtil {
    @Autowired
    private AliOssConfig aliOssConfig;

    /**
     * 从阿里云下载照片并转base64
     */
    public String downAliPicture(String bucketName,  String objectName) {
        String base64Str;
        String accessKeyId = aliOssConfig.getKeyId();
        String accessKeySecret = aliOssConfig.getKeySecret();
        String endPoint = aliOssConfig.getEndpoint();
        OSS ossClientBean = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        try (OSSObject ossObject = ossClientBean.getObject(bucketName, objectName)) {
            base64Str = downloadFileAndConvertToBase64(ossObject);
            return base64Str;
        } catch (Exception e) {
            log.error("下载照片失败:" + e.getMessage());
            throw new BjcaBizException("下载照片失败:" + e.getMessage());
        }
    }

    /**
     * 下载文件并转换成Base64字符串
     *
     * @return base64字符串
     */
    public String downloadFileAndConvertToBase64(OSSObject optionalOssObject) {
        if (optionalOssObject == null || optionalOssObject.getObjectContent() == null) {
            return null;
        }
        try (InputStream content = optionalOssObject.getObjectContent();
             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = content.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            byte[] fileBytes = byteArrayOutputStream.toByteArray();
            return Base64.getEncoder().encodeToString(fileBytes);
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new RuntimeException("Failed to download or encode file", e);
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值