springboot中上传图片到阿里云的oss云存储

上篇演示了如何将图片上传到本地,但是在实际项目中,这样是很占服务器存储空间的。所以,我们一般的解决方案是使用oss云存储。这里就结合阿里云的oss来实现下这个业务功能。

安装依赖

参考官网即可,https://help.aliyun.com/zh/oss/developer-reference/java-installation?spm=a2c4g.11186623.0.0.5e2f480coYc6ZA

xml 复制代码
 <dependency>
     <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>3.17.4</version>
  </dependency>

代码实现

java 复制代码
/**
     * 上传到阿里云oss
     * @param image
     * @return
     * @throws Exception
     */

    @PostMapping
    public Result upload(MultipartFile image) throws Exception {
        log.info("文件上传成功 {}",image.getOriginalFilename());
        String originalFilename = image.getOriginalFilename();
        String url = aliOSSUtils.upload(image);
        return Result.success(url);
    }
  • 封装阿里云的oss上传方法
    bucketName ,accessKeyId,accessKeySecret一定要用自己申请到的
java 复制代码
package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

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

@Component
public class AliOSSUtils {
    private String endpoint = "https://oss-cn-guangzhou.aliyuncs.com";
    // 填写Bucket名称,例如examplebucket。
    private String bucketName = ";
    private String accessKeyId = "";
    private String accessKeySecret = "";

    public String upload(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String filename = UUID.randomUUID().toString() + extname;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
        ossClient.putObject(bucketName, filename, inputStream);
        String url = endpoint.split("//")[0] + "//"  + bucketName + "." + endpoint.split("//")[1] +"/" + filename;
        // 关闭OSSClient。
        ossClient.shutdown();
        return url;
    }
}

根据不同的上传需求,选择官网写好的demo代码,demo链接

https://help.aliyun.com/zh/oss/developer-reference/simple-upload-11?spm=a2c4g.11186623.0.0.610d23bfPTrcOO#section-nwx-2uy-oqp

  • 上传成功后,在bucket列表里面查看上传的文件列表

    点击文件右边的详情,就能看到具体信息

    这样,我们在新增/编辑员工信息的时候,就可以增加员工的头像图片了


正常情况下,我们在列表中就能看到新增的这条数据了。

数据库中的信息,这样也就完成了文件上传的基础功能


代码优化

配置信息,现在我们还写在工具类里面,硬编码了,这样不利于维护,于是我们改造代码,使用springboot的注解来解耦

用自己申请大账号,注意不要引号和分号,否则会报错

xml 复制代码
# 阿里云oss的配置
aliyun.oss.bucketName = 
aliyun.oss.accessKeyId = 
aliyun.oss.accessKeySecret = 
aliyun.oss.endpoint = 

工具类方法
@Value是引用的import org.springframework.beans.factory.annotation.Value;,不是lombok里面的

java 复制代码
package com.itheima.utils;

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

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

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

@Component
public class AliOSSUtils {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    public String upload(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String filename = UUID.randomUUID().toString() + extname;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
        ossClient.putObject(bucketName, filename, inputStream);
        String url = endpoint.split("//")[0] + "//"  + bucketName + "." + endpoint.split("//")[1] +"/" + filename;
        // 关闭OSSClient。
        ossClient.shutdown();
        return url;
    }
}

重启服务,测试后一切正常。

  • 自定义的阿里云配置信息爆红的解决方法
xml 复制代码
 <dependency>
    <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-configuration-processor</artifactId>
 </dependency>

重新启动,在重新输入即可

相关推荐
Spider Cat 蜘蛛猫4 小时前
Springboot SSO系统设计文档
java·spring boot·后端
zyk_computer6 小时前
AI 时代,或许 Rust 比 Python 更合适
人工智能·后端·python·ai·rust·ai编程·vibe coding
雨辰AI6 小时前
SpringBoot3 项目国产化改造完整流程|从 MySQL 到人大金仓落地
java·数据库·后端·mysql·政务
GreenTea7 小时前
【Rust 2026教程:从零构建 Mini-OLAP 引擎】第 6 章 Benchmark 与优化路线图
后端
Rust语言中文社区7 小时前
【Rust日报】2026-05-14 Pyrefly v1.0 正式发布:快速的 Python 类型检查器和语言服务器
开发语言·后端·python·rust
GreenTea8 小时前
【Rust 2026教程:从零构建 Mini-OLAP 引擎】第 5 章 SQL → 逻辑计划 → 物理计划
后端
GreenTea8 小时前
【Rust 2026教程:从零构建 Mini-OLAP 引擎】第 4 章 哈希聚合:GROUP BY 的核心
后端
IT_陈寒8 小时前
Vue的v-for为什么不加key也能工作?我差点翻车
前端·人工智能·后端
GreenTea8 小时前
【Rust 2026教程:从零构建 Mini-OLAP 引擎】第 3 章 表达式系统:把 SQL 表达式变成可执行树
后端
GreenTea8 小时前
【Rust 2026教程:从零构建 Mini-OLAP 引擎】第 2 章 向量化执行:让 CPU 跑满
后端