7.阿里云OSS
阿里云OSS
一 、概述
对象存储服务(Object Storage Service,OSS)是一种海量、安全、低成本、高可靠的云存储服务,适合存放任意类型的文件。容量和处理能力弹性扩展,多种存储类型供选择,全面优化存储成本。
地址:https://www.aliyun.com/product/oss
二、官网示例代码(上传Byte数组)
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import java.io.ByteArrayInputStream;
public class Demo {
public static void main(String[] args) throws Exception {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
String objectName = "exampledir/exampleobject.txt";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 填写Byte数组。
byte[] content = "Hello OSS".getBytes();
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));
} 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 (ClientException 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();
}
}
}
}
三、项目代码开发
3.1在tanhua-app-server模块的测试模块新建OssTest测试Oss
案例:上传本地照片到阿里云oss
public class OssTest {
public static void main(String[] args) throws Exception {
//1.要上传的图片本地路径
String filePath = "C:\\Users\\acer\\Pictures\\Saved Pictures\\QQ图片20201217124509.jpg";
//2.本地字节输入流管道
FileInputStream fis =new FileInputStream(filePath);
//3.上传到阿里云oss的图片存放位置
String fileName = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
+"/"+ UUID.randomUUID().toString()+filePath.substring(filePath.lastIndexOf("."));
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "LPAI5tB4unCVExN7BqhF46eb";
String accessKeySecret = "JOPqoNq1j4wIuRktCYRTYpISxQTE1F";
// 填写Bucket名称,例如examplebucket。
String bucketName = "project-of-tanhua";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建PutObject请求。
ossClient.putObject(bucketName, fileName,fis);
} 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 (ClientException 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();
}
}
}
3.2抽取模板工具
(1).在tanhua-app-server中的application.yml配置阿里云oss信息
tanhua:
oss:
endpoint: https://oss-cn-hangzhou.aliyuncs.com
accessKey: LTAI5tB4unCVExN7BqhF46eb
secret: JTPqoNq1j4wIuRktCYRTYpISxQTE1F
bucketName: project-of-tanhua
url: https://project-of-tanhua.oss-cn-hangzhou.aliyuncs.com
(2)OssProperties
在tanhua-autoconfig模块中新建与application.yaml配置对应的属性类
package com.tanhua.autoconfig.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "tanhua.oss")
public class OssProperties {
private String endpoint;
private String accessKey;
private String secret;
private String bucketName;
private String url;
}
(3)OssTemplate
tanhua-autoconfig创建模板对象
package com.tanhua.autoconfig.template;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.tanhua.autoconfig.properties.OssProperties;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* 文件上传组件,oss模板
*/
public class OssTemplate {
private OssProperties ossProperties;
public OssTemplate(OssProperties ossProperties) {
this.ossProperties = ossProperties;
}
/**
* 图片上传;
*参数:1.文件名
* 2.输入流
*/
public String upload(String fileName, InputStream inputStream) throws FileNotFoundException {
/**
* 这个是上传到了阿里云Oss文件的存放目录格式
* /yyyy/MM/dd/xxx.jpg
*/
String fileLocation= new SimpleDateFormat("yyyy/MM/dd").format(new Date())
+"/"+ UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = ossProperties.getEndpoint();
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = ossProperties.getAccessKey();
String accessKeySecret = ossProperties.getSecret();
// 填写Bucket名称,例如examplebucket。
String bucketName = ossProperties.getBucketName();
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建PutObject请求。
ossClient.putObject(bucketName, fileLocation, 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 (ClientException 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();
}
}
String url = ossProperties.getUrl()+"/"+fileLocation;
return url;
}
}
(4).TanHuaAutoConfiguration
package com.tanhua.autoconfig;
import com.tanhua.autoconfig.properties.OssProperties;
import com.tanhua.autoconfig.properties.SmsProperties;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
/**
* 配置类
*/
@EnableConfigurationProperties({
SmsProperties.class,
OssProperties.class
})
public class TanHuaAutoConfiguration {
@Bean
public SmsTemplate smsTemplate(SmsProperties smsProperties){
return new SmsTemplate(smsProperties);
}
@Bean
public OssTemplate ossTemplate(OssProperties ossProperties){
return new OssTemplate(ossProperties);
}
}
3.3测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AppServerApplication.class)
public class OssTest {
@Autowired
private OssTemplate ossTemplate;
@Test
public void testUpLoad() throws FileNotFoundException {
String filePath = "C:\\Users\\acer\\Pictures\\Saved Pictures\\QQ图片20211109001622.jpg";
FileInputStream fileInputStream =new FileInputStream(filePath);
String file = ossTemplate.upload(filePath, fileInputStream);
System.out.println(file);
}
}