前提是注册阿里云账号,开通OSS服务,最好创建子账户AccessKey,并为其添加响应oss管理权限。
了解OSS基本术语:
基本概念 - 对象存储 OSS - 阿里云z
在使用前我们必须先创建Bucket:
只是学习使用一两次的,存储类型可以 低频访问存储。计费案例:
计费案例 - 对象存储 OSS - 阿里云
方式一:
直接参考阿里文档接入oss sdk依赖
com.aliyun.oss
aliyun-sdk-oss
3.10.2
参考地址:安装 - 对象存储 OSS - 阿里云https://help.aliyun.com/document_detail/32009.html
参考官网文件上传demo,如下图,将之前创建的子账户accessKeysId和accessKeySecret以及创建Bucket对应的名称(bucketName)和Endpoint带入其中,然后设置想要上传上去后的在oss上展示的文件名称和路径(objectName包含路径和文件名),最后替换掉想要上传的文件的路径(filePath)就可以了
地址:如何使用流式上传和文件上传方式上传文件_对象存储 OSS-阿里云
然后执行代码,如果顺利的话应该会在对应的bucket下看到你上传的文件了。
方式二:
接入springcloud依赖
com.alibaba.cloud
spring-cloud-starter-alicloud-oss
2.2.0.RELEASE
com.alibaba.cloud
spring-cloud-alibaba-dependencies
2021.0.1.0
pom
import
application.yml配置oss配置:
spring:
cloud:
alicloud:
access-key: nideaccesskyeid
secret-key: youraccesssecret
oss:
endpoint: oss-cn-beijing.aliyuncs.com
编写测试代码:
//自动注入
@Autowired
OSSClient ossClient;
@Test
public void testOss(){
String filePath= "C:\Users\abc\Desktop\quan.jpg";
try {
InputStream inputStream = new FileInputStream(filePath);
// 创建PutObject请求。
ossClient.putObject("bucketname", "test/quan.jpg", 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());
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
System.out.println("上传完成");
}
不出意外的话也应该会在相应的Bucket下看到上传的文件。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)