整合阿里云OSS 对象存储

1. 创建Bucket

在这里插入图片描述

  • 填写属性参数
    外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

2. 获取秘钥accessKey

2.1 进入accessKey管理页面

在这里插入图片描述

2.2 创建accessKey,并获取信息

  • 需要自行进行安全验证
    在这里插入图片描述

  • 记录自己的 信息
    在这里插入图片描述

3. 查看官方SDK文档

  • 位置
    在这里插入图片描述

  • 找到开发参考Java
    在这里插入图片描述

4. 具体实现-参考官网

4.1 添加依赖

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.15.1</version>
</dependency>

如果使用的是Java 9及以上的版本,则需要添加JAXB相关依赖。添加JAXB相关依赖示例代码如下:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.3</version>
</dependency>

4.2 配置文件添加权限秘钥

注:下面的配置记得替换为自己的

properties:

#不同的服务器,地址不同
aliyun.oss.file.endpoint=oss-cn-hangzhou.aliyuncs.com
aliyun.oss.file.keyid=LTAI5tPDostiVZjxq7LL4TDGfaf
aliyun.oss.file.keysecret=eKA03dmSMvizkec4Ij5ksNPWfafaSqDi7P
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=oss-test

yaml:

aliyun:
  oss:
    file:
      endpoint: oss-cn-hangzhou.aliyuncs.com
      keyid: LTAI5tPDostiVZjxq7LL4TDGfaf
      keysecret: eKA03dmSMvizkec4Ij5ksNPWfafaSqDi7P
      bucketname: oss-demo

4.3 添加常量类读取配置

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
//@ConfigurationProperties(prefix = "aliyun.oss.file")
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.filehost}")
//    private String fileHost;

    @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;
//    public static String FILE_HOST ;

    @Override
    public void afterPropertiesSet() throws Exception {

        END_POINT = endpoint;
        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
        BUCKET_NAME = bucketName;
//        FILE_HOST = fileHost;

    }
}

4.4 编写上传文件服务

  • 也可以封装为工具类方法
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.rjx.oss.service.OssService;
import com.rjx.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFileAvatar(String type,MultipartFile file) {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = ConstantPropertiesUtil.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        // 填写Bucket名称,例如examplebucket。
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String filename = file.getOriginalFilename();
            //随机生成唯一的值,防止文件覆盖
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            filename = uuid + filename;
            //获取当前时间
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //拼接,按日期文件夹进行分类
            filename = type + "/" datePath + "/" + filename;
            // 创建PutObject请求。
            ossClient.putObject(bucketName, filename, inputStream);
            //把上传的文件路径进行返回
            //https://oss-test.oss-cn-hangzhou.aliyuncs.com/1.jpg
            String url = "https://"+ bucketName + "." + endpoint + "/" + filename;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot可以通过整合阿里云OSS对象存储服务来实现文件上传和管理功能。具体实现可以参考以下步骤: 1. 在service层定义FileService接口,该接口包含上传文件到阿里云OSS的方法。例如,可以使用MultipartFile作为参数,返回上传成功后的文件URL。 2. 在controller层编写FileApiController类,该类使用@RestController注解标识为控制器,并使用@RequestMapping注解指定请求路径。在该类中,通过@Autowired注入FileService,并在文件上传的接口方法中调用FileService的上传文件方法并返回上传成功后的文件URL。 3. 在配置文件中配置阿里云OSS的相关信息,包括accessKey、secretKey、bucketName等。可以使用SpringBoot提供的@ConfigurationProperties注解来读取配置文件中的信息。 4. 在pom.xml文件中添加阿里云OSS SDK的依赖。 5. 编写上传文件的前端界面,可以使用HTML或者前端框架如Vue.js、React等。 通过以上步骤的实现,SpringBoot就可以整合阿里云OSS对象存储服务,实现文件上传和管理功能。这样可以将文件存储在阿里云OSS中,提高文件的安全性和可靠性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot整合阿里云OSS对象存储服务的实现](https://download.csdn.net/download/weixin_38649091/12721580)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [全网最详细SpringBoot、SpringCloud整合阿里云OSS对象存储服务](https://blog.csdn.net/weixin_55076626/article/details/127924003)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值