springboot集成阿里云OSS对象存储简单使用

一、对象存储介绍(OSS是什么)

阿里云对象存储OSS(Object Storage Service)是一款海量、安全、低成本、高可靠的云存储服务,提供99.9999999999%(12个9)的数据持久性,99.995%的数据可用性。多种存储类型供选择,全面优化存储成本。非常适合存储非结构化数据,例如视频、图形、日志、文本文件以及各种App应用、多终端同步软件、网盘下载站的文件等,单个文件的大小从1字节到48.8TB,可以存储的个数无限制。

二、如何使用

  (1)登录阿里云:https://www.aliyun.com

  (2)开通阿里云对象存储服务:对象存储OSS_云存储服务_企业数据管理_存储-阿里云

  开通完之后在右上角 个人信息->AccessKey管理可以看到生成了一个AccessKey IDAccessKey Secret注意一定要保存好!!!这两个是访问阿里云 API 的密钥,具有对应账户完全的权限,且AccessKey Secret之后就查看不了了。

三、代码部分

controller层

package com.ruoyi.web.controller.oss;

import com.ruoyi.oss.service.IOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
public class FileController {
    @Autowired
    private IOssService ossService;
    /**
     * 上传文件
     * @param file 文件
     * @return
     */
    @RequestMapping("/upload")
    public Map<String,Object> uploadFile(MultipartFile file) {
        //调用service层实现上传
        String url = ossService.uploadFile(file);
        Map<String,Object> map = new HashMap<>();
        if (url==null){
            map.put("code",5000);
            map.put("msg","上传失败");
            return map;
        }
        map.put("code",2000);
        map.put("msg","上传成功");
        map.put("url",url);
        return map;
    }
}

 service

public interface IOssService {
    public String uploadFile(MultipartFile file);
}

 实现类

package com.ruoyi.oss.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.ruoyi.oss.service.IOssService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Auther: yang
 * @Date:2023/07/11/14:46
 */
@Service
public class OssServiceImpl implements IOssService {
    @Value("${aliyun.oss.file.end-point}")
    String endpoint;
    @Value("${aliyun.oss.file.access-key-id}")
    String accessKeyId;
    @Value("${aliyun.oss.file.access-key-secret}")
    String accessKeySecret;
    @Value("${aliyun.oss.file.bucket-name}")
    String bucketName;

    @Override
    public String uploadFile(MultipartFile file) {
        long l = System.currentTimeMillis();
        //获取文件名
        String fileName = l+"."+file.getOriginalFilename();
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

        try {
            //获得文件流
            InputStream inputStream = file.getInputStream();
            //创建putObject请求
            ossClient.putObject(bucketName,fileName,inputStream);
            //返回拼接后oss访问路径
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        }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());
            return null;
        }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());
            return null;
        }catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

我这里命名上传后的文件名为当前时间戳.文件名(可以改成自己想要的格式)

AccessKey Id和AccessKey secret是我们生成的阿里云api密钥

bucketName就是对应bucket的名字

endpoint:进入bucket列表->点击对应的bucket->概览->复制访问端口中的外网访问的Endpoint

application.yml(在配置文件中配置OSS)

      #配置阿里云oss
      aliyun:
        oss:
          file:
            end-point: 你的endpoint
            access-key-id: 你的accesskey Id
            access-key-secret: 你的accessKey secret
            bucket-name: 你的bucketName

       到这里我们就可以调用接口正常的上传文件了,不过我这个对象存储有个问题,可以接受任意类型的文件上传,但是在前端页面只能显示图片类型的,例如txt文件就无法查看,看了别人的博客有的说是需要加上自己的域名才能正常显示,不过我还没有尝试,大家可以试一试,如果可以的话可以留言告诉我一下。

       另外我刚接触对象存储,很多地方存在不足,这个只能算是解决一时之需,如果想深入了解对象存储,可以互相交流一下,乐意接受批评!

       谢谢浏览!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值