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); } } }
04-10
2718