Version background: springboot:2.4.12, spring-cloud:2020.0.1
When using Alibaba Cloud Object Storage OSS service, follow the official reference document: aliyun-spring-boot/aliyun-spring-boot-samples/aliyun-oss-spring-boot-sample at master · alibaba/aliyun-spring-boot · GitHub
There is a problem that the dependency cannot be downloaded, there is no maven configuration problem, and the compilation reports the following problems
After adding the version, there is no compilation error, but the operation will still report an error, as follows:
Solution: Change dependencies
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
Java code
@Autowired
private OSSClient ossClient;
@Test
void testUpload2() throws ClientException {
// 填写Bucket名称,例如examplebucket。
String bucketName = "xw-bucket-test";
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
String objectName = "xw/小王Test.txt";
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
String filePath = "D:\\小王Test.txt";
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 (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
System.out.println("upload seccess!");
}
application.yml
apring:
cloud:
alicloud:
oss:
endpoint: oss-cn-shanghai.aliyuncs.com
access-key: LTAI5tMk2tq7yqzNPxTwRLks
secret-key: ByS15Y7Xm2kaBBKYrIkrpYDT1sbsCM
Test Results