一、使用阿里云oss存储文件
1.什么是阿里云oss?
OSS 为 Object Storage Service,即对象存储服务。是阿里云提供的海量、安全、低成本、高可靠的云存储服务。
OSS 具有与平台无关的 RESTful API 接口,可以在任意应用、任意时间、任意地点 存储与访问 任何类型的数据。
简单地理解:OSS 基于网络提供数据存储服务,通过网络可以随时存储、获取 文本、图片、音频、视频等 非结构化数据。
比如网站的 图片、视频等文件就可以存放在 OSS 中(海量数据,自己维护起来麻烦,交给其他人去维护),每次从 OSS 中获取即可。
2.项目中如何使用阿里云oss
2.1开通阿里云oss创建bucket
(1)打开https://www.aliyun.com/ ,申请阿里云账号并完成实名认证。
(2)搜索oss并且点击
(3)点击管理控制台(先使用赠送的那点)
(4)点击bucket列表,并且创建bucket,把读写权限改为公共读
(5)然后就可以上传图片了
(6)申请密钥,你找到这里自己就会申请了,我就不教了。
2.2编写配置属性类,yml文件di注入配置属性类,配置类使用,方便修改配置信息
先导入依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
(1)编写配置属性类
@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
(2)ymlDI注入
alioss:
endpoint: oss-cn-beijing.aliyuncs.com //访问文件服务器的地址
access-key-id: 密钥上的keyid
access-key-secret: 密钥
bucket-name: 你的bucket包名
(3)放入工具类,里面通过创建ossclient传给其他服务器,输入跨域访问的一种。
@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
/**
* 文件上传
*
* @param bytes
* @param objectName
* @return
*/
public String upload(byte[] bytes, String objectName) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
} 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();
}
}
//文件访问路径规则 https://BucketName.Endpoint/ObjectName
StringBuilder stringBuilder = new StringBuilder("https://");
stringBuilder
.append(bucketName)
.append(".")
.append(endpoint)
.append("/")
.append(objectName);
log.info("文件上传到:{}", stringBuilder.toString());
return stringBuilder.toString();
}
}
(4)创建配置类
@Configuration
@Slf4j
public class OssConfiguration {
@Bean
@ConditionalOnMissingBean
// @ConditionalOnMissingBean 是一个 Spring 引导注解,仅当应用程序上下文中没有相同类型的现有 Bean 时,它才用于有条件地创建 Bean。它通常用于配置类或组件类中,以根据特定 Bean 的存在与否来定制 Bean 创建过程。
public AliOssUtil AliOssUtil(AliOssProperties aliOssProperties) {
log.info("开始创建阿里云文件上传工具类对象:{}", aliOssProperties);
return new AliOssUtil(
aliOssProperties.getEndpoint(),
aliOssProperties.getAccessKeyId(),
aliOssProperties.getAccessKeySecret(),
aliOssProperties.getBucketName()
);
}
}
(5)图片上传接口
@RestController
@RequestMapping("/admin/common")
public class CommonController {
@Autowired
private AliOssUtil aliOssUtil;
@PostMapping("/upload")
public Result<String> upload(MultipartFile file) {
try {
String originalFilename = file.getOriginalFilename();
String extension = null;
if (originalFilename != null) {
extension = originalFilename.substring(originalFilename.lastIndexOf("."));
}
String objectName = UUID.randomUUID().toString() + extension;
String filePath = aliOssUtil.upload(file.getBytes(), objectName);
return Result.success(filePath);
} catch (IOException e) {
}
return Result.error("****");
}
}