全网最详细SpringBoot、SpringCloud整合阿里云OSS对象存储服务

news2025/8/12 21:12:07

1、进入阿里云官网

https://www.aliyun.com/

2、搜索“对象存储OSS”

3、进入“管理控制台”

4、进入“Bucket列表”,点击“创建Bucket”

5、根据实际情况选择,最后点击“确定”

这里插入一个可以通过代码创建Bucket的测试类,如下:

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

public class OssTest {
    public static void main(String[] args) {
        String endpoint = "https://oss-cn-shanghai.aliyuncs.com";
        String accessKeyId = "LTAI5tRo9YESJJp2EjPscF1h";
        String accessKeySecret = "UhClPCgctvM0gZdcppsCc0vTMOVuKm";
        String bucketName = "sgg-yygh-syt-test";

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

        //创建存储空间
        ossClient.createBucket(bucketName);

        //关闭OSSClient
        ossClient.shutdown();

    }
}

6、点击“文件列表”,选择“上传文件”

7、选择“扫描文件”,顺便选择一张图片后,再点击“上传文件”

8、返回文件列表,点击“详情”

9、复制url,粘贴到浏览器上就可以下载此文件了

以上均为控制台操作文件,下面展示通过代码操作

10、选择“AccessKey管理”

11、点击“创建AccessKey”

12、创建成功后,把“AccessKey ID”和“AccessKey Secret”复制下来,后面要用

13、开始代码开发,引入依赖,如果是SpringBoot项目就不用加nacos依赖

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.15.1</version>
</dependency>
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.1</version>
</dependency>        
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <version>2.2.0.RELEASE</version>
</dependency>

14、添加配置文件application.properties,SpringBoot项目就不用加nacos的配置了

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

#返回json的全局时间格式.
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

# nacos服务地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

aliyun.oss.endpoint=oss-cn-shanghai.aliyuncs.com
aliyun.oss.accessKeyId=LTAI5tRo9YESJJp2EjPscF1h
aliyun.oss.secret=UhClPCgctvM0gZdcppsCc0vTMOVuKm
aliyun.oss.bucket=sgg-yygh-syt

aliyun.oss.accessKeyId=LTAI5tRo9YESJJp2EjPscF1h
aliyun.oss.secret=UhClPCgctvM0gZdcppsCc0vTMOVuKm

aliyun.oss.endpoint=oss-cn-shanghai.aliyuncs.com

aliyun.oss.bucket=sgg-yygh-syt

15、添加启动类,SpringBootApplication的

(exclude=DataSourceAutoConfiguration.class)

和EnableDiscoveryClient注解看情况加

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源自动配置
@EnableDiscoveryClient//开启nacos注册中心
@ComponentScan(basePackages = {"com.hospital"})//可以扫描到另一个模块的swagger
public class ServiceOssApplication {
    public static void main(String[] args) {
      SpringApplication.run(ServiceOssApplication.class, args);
   }
}

16、创建ConstantOssPropertiesUtils配置类

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ConstantOssPropertiesUtils implements InitializingBean {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.secret}")
    private String secret;

    @Value("${aliyun.oss.bucket}")
    private String bucket;

    public static String EDNPOINT;
    public static String ACCESS_KEY_ID;
    public static String SECRECT;
    public static String BUCKET;

    @Override
    public void afterPropertiesSet() throws Exception {
        EDNPOINT=endpoint;
        ACCESS_KEY_ID=accessKeyId;
        SECRECT=secret;
        BUCKET=bucket;
    }
}

17、编写controller,service,serviceImpl

controller层:

import com.hospital.common.result.Result;
import com.hospital.oss.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/oss/file")
public class FileApiController {
    @Autowired
    private FileService fileService;

    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file){
        //获取上传文件
        String url = fileService.uploadFile(file);
        return Result.ok(url);
    }
}

service层:

import org.springframework.web.multipart.MultipartFile;

public interface FileService {
    //上传文件到阿里云oss
    String uploadFile(MultipartFile file);
}

serviceImpl层:

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.hospital.oss.service.FileService;
import com.hospital.oss.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public String uploadFile(MultipartFile file) {
        //获取ConstantOssPropertiesUtils中的属性
        String endpoint = ConstantOssPropertiesUtils.EDNPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRECT;
        String bucketName = ConstantOssPropertiesUtils.BUCKET;
        try {
            //创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //上传文件流
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //生成随机唯一值,使用uuid,添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = uuid+fileName;
            //按照当前日期,创建文件夹,上传到创建文件夹里面
            //2021/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl+"/"+fileName;
            //调用方法实现上传
            ossClient.putObject(bucketName, fileName, inputStream);
            //关闭OSSClient。
            ossClient.shutdown();
            //上传之后文件路径
            //https://yygh-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            //返回
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

18、swagger上传文件测试

19、打开阿里云OSS文件列表查看

最后, 整合阿里云OSS对象存储服务成功!!! 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/15019.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

什么是供应商管理?为什么它很重要?

**供应商管理**是确保企业付给供应商的钱获得最大价值的过程&#xff0c;且目标是确保与供应商签订的所有合同都能满足企业业务的需求。 乍一看&#xff0c;供应商管理似乎是一件很容易总结的事情&#xff0c;建立适当的关系&#xff0c;管理需求&#xff0c;并与供应商进行清…

VR直播系统设置大揭秘,带你穿越时空亲临现场

直播现在可谓是各个行业的香饽饽&#xff0c;不管是电商带货直播&#xff0c;还是游戏竞赛直播都是如火如荼。而VR直播也逐渐频繁出现在大众眼前&#xff0c;就例如前两年广大人民都是通过VR直播在线观看火神山的建设&#xff0c;随着近两年5G技术和VR技术的兴起和发展&#xf…

MongoDB安装及进程介绍

文章目录 MongoDB安装重要的进程介绍mongo进程其他进程MongoDB安装 MongoDB 官方已经提供了Linux、Windows、Mac OS X 以及Solaris 4 种平台的二进制分发包,最新的稳定版本是 6.0.2,下载地址是:https://www.mongodb.com/try/download/community,如图: 下载完成后,解压…

Vue3源码解读之patch

例子代码 本篇将要讲解dom diff&#xff0c;那么咱们结合下面的例子来进行讲解&#xff0c;这个例子是在上一篇文章的基础上&#xff0c;加了一个数据变更&#xff0c;也就是list的值发生了改变。html中增加了一个按钮change&#xff0c;通过点击change按钮来调用change函数&a…

Java语法之封装

我们应该都知道Java面向对象的三大特性&#xff1a;封装&#xff0c;继承&#xff0c;多态&#xff0c;今天小编给大家分享封装这个概念以及使用&#xff0c;我们开始吧&#xff1a; 目录 &#x1f389;封装的概念 &#x1f389;封装的使用 &#x1f389;封装的好处 &#…

论文写作:word连续交叉引用

文章目录一、问题背景二、步骤一、问题背景 在写作得时候&#xff0c;使用word的 “交叉引用”功能可以形成超链接格式的标号。但是交叉引用每次只能选择一篇论文&#xff0c;在连续选择多篇论文的时候&#xff0c;就是 “[1][2][3]” 而不是 “[1-3]” 这样的格式。 如图&…

redis set zset key 常用命令

list 可以重复 set不可以 list 有序 set元素位置无序 key常用命令 #1. 存储数据 sadd key member [member ...] 获取的结果是无序的 #2. 获取数据&#xff08;获取全部数据&#xff09; smembers key #3. 随机获取一个数据&#xff08;获取的同时&#xff0c;移除数据&#…

22.11.17打卡 mysql学习笔记

为了不挂科...... 内连接 2022年11月17日 19:34 分为隐式内连接和显式内连接 区别是: 表的连接形式和链接条件的表现形式; 链接条件的表现形式 隐式内连接 显式内连接 外连接 2022年11月17日 19:44 外连接分为左外连接和右外连接 左外连接 右外连接 自连接 2022年11月17…

为什么vue3要选用proxy,好处是什么?

提问 Object.defineProperty()和proxy的区别&#xff1f;为什么vue3要选用proxy&#xff0c;好处是什么&#xff1f; proxy Proxy 对象用于创建一个对象的代理&#xff0c;从而实现基本操作的拦截和自定义&#xff08;如属性查找、赋值、枚举、函数调用等&#xff09;。 Pr…

微软推出Azure量子资源估算器,加速量子算法研发

​ &#xff08;图片来源&#xff1a;网络&#xff09; 近期&#xff0c;微软推出了Azure量子资源估算器&#xff0c;以帮助研发人员检查他们的算法是否可以在未来规模化的量子计算机上运行&#xff0c;并在不同硬件之间进行比较&#xff0c;同时估算在这些系统上执行量子应用…

JVM——垃圾回收机制和内存分配策略

文章目录垃圾回收的垃圾是什么如何判断一个对象是不是垃圾引用计数法可达性分析算法Java的引用垃圾回收基础算法标记清除标记整理标记复制分代垃圾回收GC分析实例HotSpot算法实现细节根节点枚举记忆集与卡表为什么需要记忆集卡表写屏障写屏障&#xff08;Write Barrier&#xf…

如何实现 MySQL 增删改查操作

文章目录1.新增1.1 不指定列插入1.2 指定列插入1.3 一次性插入多行2.查询2.1 全列查询&#xff08;查询表中的所有列&#xff09;2.2 指定列查询2.3 在查寻过程中进行简单计算&#xff08;列和列之间&#xff09;2.4 给查询结果的列指定一个别名2.5 查询的时候针对列来去重&…

【AI绘画 | draft意间】国产draft推荐及AI绘画背后的原理解读

个人名片&#xff1a; &#x1f43c;作者简介&#xff1a;一名大二在校生&#xff0c;喜欢编程&#x1f38b; &#x1f43b;‍❄️个人主页&#x1f947;&#xff1a;小新爱学习. &#x1f43c;个人WeChat&#xff1a;hmmwx53 &#x1f54a;️系列专栏&#xff1a;&#x1f5bc…

计算机网络—网络层

网络协议 IP 概述 因为网络层是整个互联网的核心&#xff0c;因此应当让网络尽可能简单。网络层提供简单灵活的、无连接的、尽最大努力交互的数据报服务。 使用 IP 协议&#xff0c;可以把异构的物理网络连接起来&#xff0c;使网络层像统一的网络 与 IP 协议配套使用有三种…

Molecular Psychiatry:神经成像预测模型在心理健康领域的未来趋势

使用神经成像数据的预测建模有潜力提高我们对精神障碍的神经生物学基础和推定的信息干预的理解。因此&#xff0c;有大量的文献回顾了已发表的研究&#xff0c;机器学习的数学基础&#xff0c;以及使用这些方法的最佳实践。随着我们在心理健康和机器学习方面的知识不断发展&…

【分布式应用】GFS分布式文件系统

文件系统&#xff1a;用于存储和管理文件的相关系统。 FS&#xff08;文件系统&#xff09;的作用:从系统角度来看&#xff0c;文件系统是对文件存储设备的空间进行组织和分配&#xff0c;负责文件存储并对存入的文件进行保护和检索的系统。 具体地说&#xff0c;它负责为用户建…

Windows重启时的电脑蓝屏怎么办?

在使用Windows电脑时&#xff0c;最害怕的是遇到系统突然崩溃的情况&#xff0c;特别是出现蓝屏。蓝屏可能会导致数据丢失、无法启动Windows等糟糕的情况。那电脑重启时蓝屏怎么解决&#xff1f; 解决方法一、使用系统还原撤消最近的更改 Windows中的系统还原功能是一个便利的…

html5+css3

目录 一、html简介&#xff1a; 1、什么是网页&#xff1f; 2、什么是html&#xff1f; 3、网页的形成 二、常用的浏览器 三、web标准&#xff08;重点&#xff09; 1、为什么要使用web标准&#xff1f; 2、遵循web标准的优点&#xff1a; 四、html语法规范 1、基本语…

Hadoop架构、组件、及其术语汇总和理解

推荐大象教程&#xff0c;介绍Hadoop、HDFS、MapReduce架构和工作原理相对来说非常的清晰。其内容是与《Hadoop the Definitive Guide》基本一致的。讲解的很细致、细节&#xff0c;又带了一些个人的理解和举例子&#xff0c;比较易懂&#xff0c;是比Hadoop官网更值得一看的入…

Assignment写作怎么避免不及格的情况出现?

俗语说得好&#xff0c;犯错误是在所难免的。中西方教育方式大不相同&#xff0c;对Assignment的写作要求也有所不同。刚到国外时&#xff0c;留学生对国外的教育制度和学习过程缺乏了解。难怪在日常学习中&#xff0c;尤其是在英文Assignment写作过程中&#xff0c;留学生都会…