25.阿里云OSS--云存储


一、开通对象存储OSS

为了解决海量数据存储与弹性扩容,项目中我们采用云存储的解决方案- 阿里云OSS。 

1、开通“对象存储OSS”服务

(1)申请阿里云账号
(2)实名认证
(3)开通“对象存储OSS”服务
(4)进入管理控制台

2、创建Bucket

选择:低频访问、公共读、不开通

3、查看并记录id和秘钥

4、OSS帮助文档

 

 

 https://help.aliyun.com/document_detail/32008.html?spm=5176.208357.1107607.21.2b6e390feDXmJ6

二、java代码操作阿里云oss

1、在service模块中创建子模块service_oss

2、在service_oss的pom文件中引入相关oss依赖

    <dependencies>
        <!-- 阿里云oss依赖 -->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
        </dependency>

        <!-- 日期工具栏依赖 -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>
    </dependencies>

3、在resources中创建配置文件application.properties

#服务端口
server.port=8002
#服务名
spring.application.name=service-oss

#环境设置:dev、test、prod
spring.profiles.active=dev

#阿里云 OSS
#不同的服务器,地址不同
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.oss.file.keyid=LTAI4GAeLQ4ByaQARKZMnXyj
aliyun.oss.file.keysecret=JSh6nc9XFq2LjRNOBBgyKMCPhEE0c7
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=edu-0317

4、创建启动类OssApplication

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class )//参数表示不加载数据库
@ComponentScan({"com.atguigu"})
public class OssApplication {
    public static void main(String[] args) {
        SpringApplication.run(OssApplication.class, args);
    }
}

 注意:由于此模块不需要操作数据库,只是做上传到oss功能,没有配置数据库,因此需要在注入@SpringBootApplication中加入对应参数。

5、创建Oss对应的bean、controller和service

在com.atguigu.oss文件夹下创建utils/ConstantPropertiesUtils类

//当项目已启动,spring接口,spring加载之后,执行接口一个方法
@Component
public class ConstantPropertiesUtils 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;

    //spring将上面值都执行之后执行下面方法
    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT = endpoint;
        ACCESS_KEY_ID = keyid;
        ACCESS_KEY_SECRET = keysecret;
        BUCKET_NAME = bucketname;
    }
}

在com.atguigu.oss文件夹下创建controller/OssController类 

@RestController
@RequestMapping("/eduoss/fileoss")
@CrossOrigin
public class OssController {

    @Autowired
    private OssService ossService;

    //上传头像的方法
    @PostMapping
    public R uploadOssFile(MultipartFile file) {
        //获取上传文件 MultipartFile
        //返回上传到oss的路径
        String url = ossService.uploadFileAvatar(file);
        return R.ok().data("url",url);
    }
}

在com.atguigu.oss文件夹下创建service/OssService接口

public interface OssService {
    //上传头像到oss
    String uploadFileAvatar(MultipartFile file);
}

在com.atguigu.oss文件夹下创建service/impl/OssServiceImpl接口实现类

@Service
public class OssServiceImpl implements OssService {

    //上传头像到oss
    @Override
    public String uploadFileAvatar(MultipartFile file) {

        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 获取上传文件输入流
            InputStream inputStream = file.getInputStream();

            //获取文件名称
            String fileName = file.getOriginalFilename();

            //1 在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            //yuy76sad1.jepy
            fileName = uuid + fileName;

            //2 把文件按照日期进行分类
            //获取当前日期
            //   2021/03/17
            String datePath = new DateTime().toString("yyyy/MM/dd");

            //拼接
            //2021/03/17/1.jepg
            fileName = datePath + "/" + fileName;

            // 调用oss方法实现上传
            //第一个参数  Bucket名称
            //第二个参数  上传到oss文件路径和文件名称  /aa/bb/01.jepg
            //第三个参数  上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //把上传之后文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            // https://edu-0317.oss-cn-beijing.aliyuncs.com/1.jpeg
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        }catch(Exception e) {
      e.printStackTrace();
      return null;
} } }

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM