阿里OSS
一、对象存储OSS
为了解决海量数据存储与弹性扩容,项目中我们采用云存储的解决方案- 阿里云OSS。
1、开通“对象存储OSS”服务【了解】
(1)申请阿里云账号
(2)实名认证
(3)开通“对象存储OSS”服务
(4)进入管理控制台https://oss.console.aliyun.com/overview
2、创建Bucket【了解】
也就是腾讯云中的存储桶,相当于是一个目录
在java代码中也是可以创建的
选择:标准存储【访问的频率不是很大的话,低频访问也是也可以的】、公共读、不开通
3、上传默认头像【了解】
创建文件夹avatar,上传默认的用户头像
4、创建RAM子用户
创建操作阿里云OSS的一个许可证
这里可以直接保存文件到你的项目中去可以方便
阿里云的开发帮助文档https://help.aliyun.com/spm=a2c4g.11186623.6.538.7c3d4981odevJt
二、使用SDK
1、创建Mavaen项目
service
中创建service_oss
模块
2、pom
<dependencies>
<!--aliyunOSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
3、配置application.properties
#服务端口
server.port=8006
#服务名
spring.application.name=service-oss
#环境设置:dev、test、prod
spring.profiles.active=dev
#阿里云 OSS
#不同的服务器,地址不同
aliyun.oss.file.endpoint=your endpoint
aliyun.oss.file.keyid=your accessKeyId
aliyun.oss.file.keysecret=your accessKeySecret
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=guli-file
4、logback-spring.xml
5、创建启动类
创建·OssApplication.java
package com.djr.ossservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import java.time.LocalDateTime;
/**
* @Program: science_source_education
* @Description
* @Author: 涛涛 * ^ *
* @Create: 2021-01-26 17:44
**/
@SpringBootApplication
@ComponentScan(basePackages = {"com.djr"})
public class OssApplication {
public static void main(String[] args) {
SpringApplication.run(OssApplication.class, args);
System.out.println("Oss模块启动成功,此刻时间为:"+ LocalDateTime.now());
}
}
6、启动项目
报错
spring boot 会默认加载org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration这个类,
而DataSourceAutoConfiguration类使用了@Configuration注解向spring注入了dataSource bean,又因为项目(oss模块)中并没有关于dataSource相关的配置信息,所以当spring创建dataSource bean时因缺少相关的信息就会报错。
解决办法:
方法1:
在@SpringBootApplication注解上加上exclude,解除自动加载DataSourceAutoConfiguration
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
方法2.:
将数据库的配置添加到配置文件中
# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/onlineeducation?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
三、实现文件上传
1、从配置文件读取常量
创建常量读取工具类: ConstantPropertiesUtil.java
使用@Value
读取application.properties
里的配置内容
用spring
的InitializingBean
的 afterPropertiesSet
来初始化配置信息,这个方法将在所有的属性被初始化后调用。
package com.djr.ossservice.config;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @Program: 常量类,读取配置文件application.properties中的配置
* @Description
* @Author: 涛涛 * ^ *
* @Create: 2021-01-26 17:51
**/
@Component
//@PropertySource("classpath:application.properties")
public class ConstantPropertiesUtil implements InitializingBean {
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
public static String END_POINT;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
/**
* 设置属性
*
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
END_POINT = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
}
}
2、文件上传
创建Service
接口:FileService.java
package com.djr.ossservice.service;
import org.springframework.web.multipart.MultipartFile;
/**
* @Description: 文件上传
* @Author: 涛涛 *^*
* @Date: 2021/1/26 17:56
*/
public interface FileService {
/**
* 文件上传至阿里云
* @param file
* @return
*/
String UploadAvatar(MultipartFile file);
}
实现: FileServiceImpl.java
参考SDK中的:Java->上传文件->简单上传->流式上传->上传文件流
package com.djr.ossservice.service.impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.djr.commonutils.R;
import com.djr.commonutils.ResultCode;
import com.djr.ossservice.config.ConstantPropertiesUtil;
import com.djr.ossservice.service.FileService;
import com.djr.servicebase.exceptionhandler.MyselfException;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileInputStream;
import java.io.InputStream;
/**
* @Program: science_source_education
* @Description
* @Author: 涛涛 * ^ *
* @Create: 2021-01-26 17:57
**/
public class FileServiceImpl implements FileService {
/**
* 文件上传至阿里云
*
* @param file
* @return
*/
@Override
public String UploadAvatar(MultipartFile file) {
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = ConstantPropertiesUtil.END_POINT;
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,
// 创建并使用RAM子账号进行API访问或日常运维,
// 请登录 https://ram.console.aliyun.com 创建。
String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件流。
try (InputStream inputStream = file.getInputStream()) {
//第一个参数是 bucket 名称
//第二个参数是 上传到oss文件路径和文件的名称
//获取文件名称
String originalFilename = file.getOriginalFilename();
ossClient.putObject(bucketName, originalFilename, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
//返回上传到oss桶中的文件的路径
//https://edcation.oss-cn-beijing.aliyuncs.com/文件名称
String url = "https://" + bucketName + "." + endpoint + "/" + originalFilename;
return url;
} catch (Exception e) {
throw new MyselfException(ResultCode.FILE_UPLOAD_ERROR, "文件上传失败");
}
}
}
3、控制层
创建controller
:FileUploadController.java
package com.djr.ossservice.controller;
import com.djr.commonutils.R;
import com.djr.ossservice.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* @Program: science_source_education
* @Description
* @Author: 涛涛 * ^ *
* @Create: 2021-01-26 18:06
**/
@Api(description="阿里云文件管理")
@CrossOrigin
@RestController
@RequestMapping("/admin/oss/file")
public class FileUploadController {
@Autowired
private FileService fileService;
/**
* 文件上传
*
* @param file
*/
@ApiOperation(value = "文件上传")
@PostMapping("/upload")
public R upload(
@ApiParam(name = "file", value = "文件", required = true)
@RequestParam("file") MultipartFile file) {
String uploadUrl = fileService.upload(file);
//返回r对象
return R.ok().message("文件上传成功").data("url", uploadUrl);
}
}
4、重启oss服务
5. 文件的唯一性
//在文件名称中添加随机唯一的值,使得多次的文件名称不一样 ,去除UUID中的-
String uuid = UUID.randomUUID().toString().replace("-","");
originalFilename=originalFilename+uuid;
6.文件进行分类【时间】
//可以设置文件的根路径,可以根据时间进分类
//获取当前的日期
LocalDate localDate = LocalDate.now();
String replace = localDate.toString().replace("-", "/");
originalFilename=replace+"/"+originalFilename;
// String replace=new DateTime().toString("yyyy/MM/dd");
5、Swagger中测试文件上传