springboot微服务实战:Java调用阿里云OSS-最精简的教程 (2020年9月 )

阿里云oss-java文档地址:https://help.aliyun.com/document_detail/32009.html?spm=a2c4g.11186623.6.805.60876d39pVplLP

安装

安装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

spring-boot-alibaba链接

删除上面的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("上传完成。。。");
    }
}

最终解决方案:服务端签名后直传

alibaba光放文档链接:https://help.aliyun.com/document_detail/31926.html?spm=a2c4g.11186623.6.1576.14c46e28h6p1jw
在这里插入图片描述

解决客户端直接访问OSS跨域问题

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值