阿里云OSS对象存储服务使用
1、点击产品,然后找到并点击对象存储OSS
2、然后点击立即开通,如果只是为了学习,简单的使用还是可以的,不需要购买
3、开通后进入OSS管理控制台界面,点击进入
Bucket列表
,然后创建一个Bucket
4、创建Bucket
5、获取Accesskey,这个密钥用于上传文件时验证身份
创建Accesskey,记得保存下来
6、查看使用实例文档,点击OSS控制台往下滑左下角的SDK下载,再点击SDK示例,再点击在文档中心打开.参考文档官方
点击左侧的SDK快速入门,然后根据文档配置环境变量
根据文档提示,再环境变量中添加
OSS_ACCESS_KEY_ID
和OSS_ACCESS_KEY_SECRET
两个变量
7.使用示例,以下是在springboot下封装好的一份上传图片的工具类,上传图片并返回图片的URL
- 添加依赖(maven)
<!--阿里云oss依赖-->
<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.15.1</version>
</dependency>
<!--Java 9及以上的版本还需要添加以下依赖-->
<dependency><groupId>javax.xml.bind</groupId><artifactId>jaxb-api</artifactId><version>2.3.1</version>
</dependency>
<dependency><groupId>javax.activation</groupId><artifactId>activation</artifactId><version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency><groupId>org.glassfish.jaxb</groupId><artifactId>jaxb-runtime</artifactId><version>2.3.3</version>
</dependency>
使用示例,创建测试工程,修改对应的id和密码等,下图为endpoint地址的获取方式
import org.junit.jupiter.api.Test;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import java.io.FileInputStream;
import java.io.InputStream;public class AliOssTest {@Testpublic void testOss(){// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。String accessKeyId = "---------------------";String accessKeySecret = "-----------------------";// 填写Bucket名称,例如examplebucket。String bucketName = "-----------";// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。String objectName = "0001.jpg";// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。String filePath= "C:\\Users\\Administrator\\Pictures\\Saved Pictures\\10.jpg";// 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);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 (Exception 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();}}}
}
实战:
- 项目结构:
- AliOSSUtils.java
package com.example.utils;import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import java.io.InputStream;
import java.util.UUID;/*** 阿里云 OSS 工具类*/
@Component
public class AliOSSUtils {@Autowiredprivate AliOSSUtileProperties aliOSSUtileProperties;String endpoint;String bucketName;EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();public AliOSSUtils(AliOSSUtileProperties aliOSSUtileProperties) throws ClientException {this.aliOSSUtileProperties = aliOSSUtileProperties;}/*** 将图片上传到云服务器并返回图片的URL路径* @param image 上传的图片* @return 图片的URL路径* @throws Exception 上传失败*/public String upload(MultipartFile image) throws Exception {endpoint = aliOSSUtileProperties.getEndpoint();bucketName = aliOSSUtileProperties.getBucketName();// 获取上传的文件的输入流InputStream inputStream = image.getInputStream();// 避免文件覆盖String[] originalFilename = image.getOriginalFilename().split("\\.");String fileName = originalFilename[0] + "_" + UUID.randomUUID().toString() + "." + originalFilename[1];//上传文件到 OSSOSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);ossClient.putObject(bucketName, fileName, inputStream);//文件访问路径String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;// 关闭ossClientossClient.shutdown();return url;// 把上传到oss的路径返回}}
- AliOSSUtileProperties
package com.example.utils;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliOSSUtileProperties {// 使用ConfigurationProperties注解进行依赖注入的前提条件是 mark// 必须配合使用@Data注解和@Component注解// 这里的成员变量名必须与yml配置文件中的变量名保持一致// 同时,必须指定prefix属性,指定yml配置文件中的前缀,这样才能找到对应的配置// 例如,这里的endpoint对应yml配置文件中的aliyun.oss.endpoint,所有这里的前缀是aliyun.ossprivate String endpoint;private String bucketName;
}// 这里的成员变量名必须与yml配置文件中的变量名保持一致// 同时,必须指定prefix属性,指定yml配置文件中的前缀,这样才能找到对应的配置// 例如,这里的endpoint对应yml配置文件中的aliyun.oss.endpoint,所有这里的前缀是aliyun.ossprivate String endpoint;private String bucketName;
}