您的位置:首页 > 健康 > 美食 > AliOss对象云存储

AliOss对象云存储

2025/1/8 23:01:43 来源:https://blog.csdn.net/SRY12240419/article/details/140926849  浏览:    关键词:AliOss对象云存储

文章目录

  • 配置第三方bean
  • 在`application.yml`中通过引用`dev`开发环境下的配置文件配置存储服务器
  • 创建配置类
  • 引入工具类
  • 创建公共接口


配置第三方bean

/*** 配置类用于创建AliOssUtil对象*/
@Slf4j
@Configuration
public class OssConfiguration {@Bean//将方法返回值交给IOC容器管理,成为IOC容器的bean对象@ConditionalOnMissingBean//只创建一个bean对象public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);return new AliOssUtil(aliOssProperties.getEndpoint(),aliOssProperties.getAccessKeyId(),aliOssProperties.getAccessKeySecret(),aliOssProperties.getBucketName());}}

application.yml中通过引用dev开发环境下的配置文件配置存储服务器

sky:jwt:# 设置jwt签名加密时使用的秘钥admin-secret-key: itcast# 设置jwt过期时间admin-ttl: 720000000# 设置前端传递过来的令牌名称admin-token-name: tokenalioss:accessKeyId: ${sky.alioss.accessKeyId}accessKeySecret: ${sky.alioss.accessKeySecret}bucketName: ${sky.alioss.bucketName}endpoint: ${sky.alioss.endpoint}
- application-dev.yml
sky:datasource:driver-class-name: com.mysql.cj.jdbc.Driverhost: localhostport: 3306database: sky_take_outusername: rootpassword: 1234alioss:accessKeyId: LTAI5tD6p1y3ASVQm69YoHGhaccessKeySecret: gyNxSnYFo9IsHi2BRwcgxTOrcYIS15bucketName: hmc-webframework01endpoint: https://oss-cn-beijing.aliyuncs.com

创建配置类


@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;}

引入工具类

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;/*** 文件上传** @param bytes* @param objectName* @return*/public String upload(byte[] bytes, String objectName) {// 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);try {// 创建PutObject请求。ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));} catch (OSSException oe) {System.out.println("Caught an OSSException, which means your request made it to OSS, "+ "but was rejected with an error response for some reason.");System.out.println("Error Message:" + oe.getErrorMessage());System.out.println("Error Code:" + oe.getErrorCode());System.out.println("Request ID:" + oe.getRequestId());System.out.println("Host ID:" + oe.getHostId());} catch (ClientException ce) {System.out.println("Caught an ClientException, which means the client encountered "+ "a serious internal problem while trying to communicate with OSS, "+ "such as not being able to access the network.");System.out.println("Error Message:" + ce.getMessage());} finally {if (ossClient != null) {ossClient.shutdown();}}//文件访问路径规则 https://BucketName.Endpoint/ObjectNameStringBuilder stringBuilder = new StringBuilder("https://");stringBuilder.append(bucketName).append(".").append(endpoint).append("/").append(objectName);log.info("文件上传到:{}", stringBuilder.toString());return stringBuilder.toString();}
}

创建公共接口

/*** 通用接口*/
@Slf4j
@RestController
@Api(tags = "通用接口")
@RequestMapping("/admin/common")
public class CommonController {@Autowiredprivate AliOssUtil aliOssUtil;/*** 文件上传* @param file* @return*/@ApiOperation("文件上传")@PostMapping("/upload")public Result<String>upload(MultipartFile file){log.info("文件上传{}",file);try {//原始文件名String originalFilename= file.getOriginalFilename();//截取扩展名String extension= originalFilename.substring(originalFilename.lastIndexOf("."));String objectName= UUID.randomUUID().toString()+extension;String filePath=  aliOssUtil.upload(file.getBytes(), objectName);return Result.success(filePath);} catch (IOException e) {log.error("文件上传失败: {}",e);}return Result.error(MessageConstant.UPLOAD_FAILED);}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com