Java使用阿里云OSS云存储服务常见问题解决方法:
1.导入依赖
<!--阿里云OSS-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>aliyun-oss-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
注意:这里依赖需要导入两个,只导入aliyun-oss-spring-boot-starter会报错(官网上文档中只添加了第一个依赖),如果报错需要添加第二个依赖(个人认为是版本问题)
整体pom.xml文件依赖(这里只展示OSS部分):
<dependencies>
<!--阿里云OSS-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>aliyun-oss-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>aliyun-spring-boot-dependencies</artifactId>
<version>1.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
配合阿里云OSS云存储服务使用效果:
@Autowired
OSSClient ossClient;
@Test
void testUpload() throws FileNotFoundException {
//上传文件流
InputStream inputStream = new FileInputStream("D:\\MyPhotoes\\curry_img.jpg");
ossClient.putObject("gulimall-hzt","curry_img.jpg",inputStream);
//关闭OSSClient
ossClient.shutdown();
System.out.println("上传完成!!");
}
在测试之前必须在配置文件加入以下配置:
alibaba:
cloud:
access-key:【your-ak】
secret-key:【your-sk】
oss:
endpoint:【***】
【】中的内容根据自己创建的AccessKey子用户以及创建的Bucket填写
注意:如果在使用时自动注入OSSClient ossClient后服务无法启动,报错提示无法找到该类,就需要将OSSClient ossClient改为OSS ossClient。
修改前:
修改后:(虽然这里idea报错,但是服务可以正常启动,控制器可以正常使用)
成功上传至OSS云存储: