携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第10天,点击查看活动详情
简单上传测试
OSS是对象存储服务,有什么用呢?把图片存储到云服务器上能让所有人都访问到!
详细操作可查官方文档,下面只写关键代码
[SDK示例 (aliyun.com)](help.aliyun.com/document_de…)
一、创建子用户测试用例
官方推荐使用子账户的AccessID和SecurityID,因为如果直接给账户的AccessID和SecurityID的话,如果不小心被其他人获取到了,那账户可是有全部权限的!!!
所以这里通过建立子账户,给子账户分配部分权限实习。
这里通过子账户管理OSS的时候,要给子账户添加操控OSS资源的权限 这里是必须要做的,因为子账户默认是没有任何权限的,必须手动给他赋予权限
二、引入依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.1.0</version>
</dependency>
三、测试用例
比较固定,直接粘贴过来拿来直接拿来用
@SpringBootTest
class MallProductApplicationTests {
@Test
public void testUploads() throws FileNotFoundException {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "。。。";
String accessKeySecret = "。。。";
// 填写Bucket名称,例如examplebucket。
String bucketName = "pyy-mall";
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
String objectName = "2022/testPhoto.txt";
// 填写本地文件的完整路径,例如D:\localpath\examplefile.txt。
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
String filePath= "C:\Users\Jack\Desktop\R-C.jfif";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = new FileInputStream(filePath);
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
} 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();
}
}
}
}
Aliyun Spring Boot OSS
更简单的方法就是通过如下文档,注入OSSClient对象即可实现上传
官方文档如下: github.com/alibaba/ali…
一、引入依赖
我们不是进行依赖管理了吗?为什么还要显示写出2.1.1版本
这是因为这个包没有最新的包,只有和2.1.1匹配的
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alicloud-oss</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
二、在配置文件中配置 OSS 服务对应的 accessKey、secretKey 和 endpoint
alicloud:
access-key: xxx
secret-key: xxx
oss:
endpoint: oss-cn-hangzhou.aliyuncs.com
三、注入OSSClient测试
@Resource
private OSSClient ossClient;
@Test
public void testUploads() throws FileNotFoundException {
// 上传文件流。
InputStream inputStream = new FileInputStream("C:\Users\Jack\Desktop\LeetCode_Sharing.png");
ossClient.putObject("pyy-mall", "2022/testPhoto2.png", inputStream);
// 关闭OSSClient。
ossClient.shutdown();
System.out.println("上传完成...");
}
\