当前位置: 首页 > news >正文

2.阿里云对象存储OSS

1.对象存储概述

        文件上传,是指将本地图片、视频、音频等文件上传到服务器上,可以供其他用户浏览或下载的过程。文件上传在项目中应用非常广泛,我们经常发抖音、发朋友圈都用到了文件上传功能。

实现文件上传服务,需要有存储的支持,解决方案有以下几种:

存储方式优点缺点
直接保存到硬盘开发便捷,成本低扩容困难
分布式文件系统容易实现扩容开发复杂,需要成熟产品支持
第三方存储服务开发简单,强大功能, 免维护付费

2.阿里云对象存储OSS

阿里云登录 - 欢迎登录阿里云,安全稳定的云计算服务平台欢迎登录阿里云,全球领先的云计算及人工智能科技公司,阿里云为200多个国家和地区的企业、开发者和政府机构提供云计算基础服务及解决方案。阿里云云计算、安全、大数据、人工智能、企业应用、物联网等云计算服务。https://oss.console.aliyun.com/

2.1 阿里云对象存储OSS配置

2.1.1 创建OSS Bucket

        登录阿里云控制台,申请ECS服务器、申请对象存储OSS、在OSS管理页面创建一个Bucket,Bucket是存储空间的容器,类似于文件夹。选择Bucket的地域、访问权限等设置。

2.1.2 获取AccessKey

        在阿里云控制台获取AccessKey ID和AccessKey Secret,这是访问OSS的凭证。

2.2 项目中使用对象存储OSS

2.2.1 配置AccessKey ID和AccessKey Secret

sky:alioss:endpoint: oss-cn-chengdu.aliyuncs.comaccess-key-secret: B4CZYBn9zyoKjQzdN5sQNvdxaWJSuyaccess-key-id: LTAI5tAKNiTtEJaPdE3omMi3bucket-name: luobeilearn

2.2.2 配置配置类

@Configuration
@Slf4j
public class OssConfiguration {@Bean@ConditionalOnMissingBeanpublic AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){log.info("开始上传阿里云文件上传工具类对象:{}",aliOssProperties);return new AliOssUtil(aliOssProperties.getEndpoint(),aliOssProperties.getAccessKeyId(),aliOssProperties.getAccessKeySecret(),aliOssProperties.getBucketName());}
}

2.2.3 创建阿里云属性类

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

2.2.4 创建工具类

@Data
@NoArgsConstructor
@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();}
}

2.2.5 在Controller中使用

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

相关文章:

  • (三)Unity开发Vision Pro——入门
  • 召集令:CloudQuery 社区有奖征文活动来啦!
  • 【傅里叶级数与傅里叶变换】数学推导——1、基础知识点回顾及[Part1:三角函数的正交性]介绍
  • BUUCTF [MRCTF2020]Ezpop解题思路
  • 【IMX6ULL驱动开发学习】07.驱动程序分离的思想之平台总线设备驱动模型和设备树
  • 深度学习中的python语法笔记总结
  • Reids 的整合使用
  • Vue3 —— watchEffect 高级侦听器
  • Java异步子线程读取主线程参数的若干好玩场景
  • Android 视频开发
  • 【计算机网络篇】UDP协议
  • LeetCode 2682. 找出转圈游戏输家
  • 数据结构单链表
  • 自定义WEB框架结合Jenkins实现全自动测试
  • PHP加密与安全的最佳实践
  • SQL Server数据库无法连接
  • videojs 播放视频
  • vue强制刷新变量
  • [QCA6174]QCA6174 5G WiFi DFS处理逻辑分析及雷达误检率高优化规避
  • 预防SQL漏洞注入和规避网络攻击
  • 《Go 语言第一课》课程学习笔记(一)
  • 网络安全 Day29-运维安全项目-iptables防火墙
  • SQL 复习 03
  • 出现 sudo: docker: command not found 的解决方法
  • FastApi-1-结合sql 增/查demo
  • Spring学习笔记3
  • springboot艰难版本升级之路!! springboot 2.3.x版本升级到2.7.x版本
  • Codeforces 1856E2 复杂度分析 + DP
  • Windows - UWP - 为UWP应用创建桌面快捷方式
  • 了解Web DDoS海啸攻击的4个维度