1.导入对应的依赖
注意版本不要选太高,就选这个2.2.0.RELEASE不然没有这个依赖包
<pring-cloud-starter-alicloud-oss>2.2.0.RELEASE</pring-cloud-starter-alicloud-oss>
2.创建RAM用户
1)复制对应的AK和SK
2)复制Endpoint
3.在java的application.yml配置文件信息
4.编写相应的代码
// 填写Bucket名称,例如examplebucket。
String bucketName = "bucketName";
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
String objectName = "gulimall/2023-07-09.png";
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
String filePath= "C:\\Users\\145123\\OneDrive\\图片\\Screenshots\\2023-07-09.png";
// 创建OSSClient实例。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
try {
InputStream inputStream = new FileInputStream(filePath);
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
// 创建PutObject请求。
PutObjectResult result = ossClient.putObject(putObjectRequest);
} 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();
}
}
System.out.println("上传成功");
可以从对应的官网引用代码
如何新建和配置OSSClient实例_对象存储(OSS)-阿里云帮助中心
然后参考我的代码修改
最后
文件上传成功