安装
安装SDK
方式一:在Maven项目中加入依赖项(推荐方式)
在Maven工程中使用OSS Java SDK,只需在pom.xml中加入相应依赖即可。以3.10.2版本为例,在中加入如下内容:
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
简单上传
上传文件流
以下代码用于上传文件流:
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件流。
InputStream inputStream = new FileInputStream("<yourlocalFile>");
ossClient.putObject("<yourBucketName>", "<yourObjectName>", inputStream);
// 关闭OSSClient。
ossClient.shutdown();
将上面代码粘贴到项目的测试方法类,新建一个方法中
1、参数:endpoint
2、参数:AccessKey
accessKeyId 与 accessKeySecret
默认新建子用户没有任何访问权限
添加权限
3、参数:yourlocalFile
C:\Users\Administrator\Desktop\20200810112850.jpg
4、参数:yourBucketName
5、 参数:yourObjectName
就是上传文件的文件名,这里自定义
springboot 结合 alibaba 使用 oss
删除上面的pom坐标
引入新pom坐标
第一步:引入pom
老版本使用
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
</dependency>
最新版本(直接使用报错)
如何解决引入pom报错not found方案链接:https://blog.csdn.net/Liu_1796997299/article/details/107896424
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>aliyun-oss-spring-boot-starter</artifactId>
</dependency>
第二步:改yaml ,谁用改谁
spring:
cloud:
alicloud:
access-key: LTAI4。。。(填写你自己的access)
secret-key: giX0。。。(填写你自己的secret)
oss:
endpoint:(填写你自己的endpoint)
第三步:使用 OSSClient
通过 @Autowired 注入到使用 oss的类中
@SpringBootTest
class GulimallProductApplicationTests {
@Autowired
OSSClient ossClient;
@Test
public void testUpload() throws FileNotFoundException {
// 上传文件流。
InputStream inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\20200810112850.jpg");
ossClient.putObject("gulimall-ctra", "20200810112850.jpg", inputStream);
// 关闭OSSClient。
ossClient.shutdown();
System.out.println("上传完成。。。");
}
}
最终解决方案:服务端签名后直传
解决客户端直接访问OSS跨域问题