文章目录
安装sdk
- 安装sdk
- 简单文件上传的代码测试
- Spring Cloud Alibaba-OSS
在对象存储的首页中, 找到文档的链接 在文档中心打开
Java sdk的安装 https://help.aliyun.com/document_detail/32009.html?spm=a2c4g.11186623.6.904.cd5758d55CFtJ7
复制如下的依赖
com.aliyun.oss
aliyun-sdk-oss
3.10.2
把此依赖复制到 gulimall-product 的pom.xml中
代码示例中有简单上传的代码示例
创建子用户, 只需要编程访问的权限
创建完子账户后, 会生成id 和key
将其复制到代码中
额外的 , 还需要对子账户进行权限的分配操作 .
如果该账户没有授权 ,则会出现如下的报错
com.aliyun.oss.OSSException: You have no right to access this object because of bucket acl.
[ErrorCode]: AccessDenied
[RequestId]: 5F72EFD63D124D34331F73EB
[HostId]: gulimall-thc-hello.oss-cn-shanghai.aliyuncs.com
[ResponseError]:
AccessDenied
You have no right to access this object because of bucket acl.
5F72EFD63D124D34331F73EB
gulimall-thc-hello.oss-cn-shanghai.aliyuncs.com
将简单文件上传的代码修改如下, 其中图片的路径为本机的路径.
@Test
void upload() throws FileNotFoundException {
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "oss-cn-shanghai.aliyuncs.com";
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
String accessKeyId = "";
String accessKeySecret = "";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件流。
InputStream inputStream = new FileInputStream("C:\\Users\\tao\\Desktop\\你的名字壁纸\\743487.jpg");
ossClient.putObject("gulimall-", "743487.jpg", inputStream);
// 关闭OSSClient。
ossClient.shutdown();
System.out.println("上传完成!!! ");
}
运行此test方法 可以看到上传完成 . 在页面中 , 也可以看到上传成功的文件
将 如下的alicloud-oss 依赖, 放入 common模块中
com.alibaba.cloud
spring-cloud-starter-alicloud-oss
在yml中进行配置秘钥 和 节点
在测试的工具类中, 直接注入
OSSClient
对象即可上传
@RunWith(SpringRunner.class)
@SpringBootTest
class GulimallProductApplicationTests {
@Autowired
OSSClient ossClient ;
@Test
void upload() throws FileNotFoundException {
// 上传文件流。
InputStream inputStream = new FileInputStream("C:\\Users\\tao\\Desktop\\天气之子壁纸\\1082262.png");
ossClient.putObject("gulimall-thc-hello", "1082262.png", inputStream);
// 关闭OSSClient。
ossClient.shutdown();
System.out.println("上传完成!!! ");
}
}
控制台打印如下
阿里云控制台中, 也可以看到
总结: 三步 :
- pom.xml中引入 oss- starter
- yml中配置秘钥和上传的节点
- 使用OSSClient 进行相关操作