springboot 集成阿里云 OSS

引入依赖
xml 复制代码
<!-- 阿里云oss依赖 -->
<dependency>
  <groupId>com.aliyun.oss</groupId>
  <artifactId>aliyun-sdk-oss</artifactId>
  <version>3.9.1</version>
</dependency>
xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.orchids</groupId>
  <artifactId>aliyun-oss</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>aliyun-oss</name>
  <description>aliyun-oss</description>
  <properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <spring-boot.version>2.7.12</spring-boot.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.github.xiaoymin</groupId>
      <artifactId>knife4j-openapi3-spring-boot-starter</artifactId>
      <version>4.1.0</version>
    </dependency>
    <!-- 阿里云oss依赖 -->
    <dependency>
      <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>3.9.1</version>
    </dependency>
    <!-- 日期工具栏依赖 -->
    <dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>2.10.1</version>
    </dependency>
  </dependencies>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>${spring-boot.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>${spring-boot.version}</version>
        <configuration>
                    <mainClass>com.orchids.aliyunoss.AliyunOssApplication</mainClass>
                    <skip>true</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
编写配置文件
yaml 复制代码
server:
  port: 8080

aliyun:
  endpoint: oss-cn-wuhan-lr.aliyuncs.com
  accessKey: your-accessKey
  secretKey: your-secretKey
  bucketname: nullpointer2024
编写配置aliyun配置类
java 复制代码
package com.orchids.aliyunoss.aliyun;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;


/**
 * @ Author qwh
 * @ Date 2024/6/27 14:38
 */
@Data
@ConfigurationProperties(prefix = "aliyun")
public class AliyunProperties {
    private String endpoint;

    private String accessKey;

    private String secretKey;

    private String bucketName;
}
java 复制代码
package com.orchids.aliyunoss.aliyun;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ Author qwh
 * @ Date 2024/6/27 14:39
 */
@Configuration
@EnableConfigurationProperties(AliyunProperties.class)
public class AliyunConfiguration {
    @Autowired
    private AliyunProperties aliyunProperties;
    @Bean
    public OSS ossClient(){
        return new OSSClientBuilder()
                .build(
                        aliyunProperties.getEndpoint(),
                        aliyunProperties.getAccessKey(),
                        aliyunProperties.getSecretKey());
    }

}
编写knife4j配置文件
java 复制代码
package com.orchids.aliyunoss.web.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springdoc.core.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ Author qwh
 * @ Date 2024/6/27 14:54
 */
@Configuration
public class Knife4jConfiguration {
    @Bean
    public OpenAPI OpenAPI() {
        return new OpenAPI().info(
                new Info()
                        .title("AliyunOSSAPI")
                        .version("1.0")
                        .description("UploadAPI"));
    }
    @Bean
    public GroupedOpenApi StudentAPI() {

        return GroupedOpenApi.builder().group("AliyunOssFile管理").
                pathsToMatch(
                        "/aliyun/**"
                ).
                build();

    }
}
结果返回类
java 复制代码
package com.orchids.aliyunoss.model.result;

import lombok.Data;

/**
 * @ Author qwh
 * @ Date 2024/6/27 14:37
 */
@Data
public class Result<T>{
    //返回码
    private Integer code;

    //返回消息
    private String message;

    //返回数据
    private T data;

    public Result() {
    }

    private static <T> Result<T> build(T data) {
        Result<T> result = new Result<>();
        if (data != null)
            result.setData(data);
        return result;
    }

    public static <T> Result<T> build(T body, ResultCode resultCodeEnum) {
        Result<T> result = build(body);
        result.setCode(resultCodeEnum.getCode());
        result.setMessage(resultCodeEnum.getMessage());
        return result;
    }


    public static <T> Result<T> ok(T data) {
        return build(data, ResultCode.SUCCESS);
    }

    public static <T> Result<T> ok() {
        return Result.ok(null);
    }

    public static <T> Result<T> fail() {
        return build(null, ResultCode.FAIL);
    }
}
controller
java 复制代码
package com.orchids.aliyunoss.web.controller;

import com.orchids.aliyunoss.model.result.Result;
import com.orchids.aliyunoss.web.service.FileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @ Author qwh
 * @ Date 2024/6/27 15:02
 */
@Tag(name = "FileUpload")
@RestController
@RequestMapping("/aliyun")
@AllArgsConstructor
public class FileUploadController {
    private final FileService fileService;

    @Operation(summary = "文件上传")
    @PostMapping("fileload")
    public Result<String> upload(@RequestParam MultipartFile file) {
        String url = fileService.upload(file);
        return Result.ok(url);
    }
}
service
java 复制代码
package com.orchids.aliyunoss.web.service;

import org.springframework.web.multipart.MultipartFile;

/**
 * @ Author qwh
 * @ Date 2024/6/27 14:56
 */
public interface FileService {
    String upload(MultipartFile file);
}
java 复制代码
package com.orchids.aliyunoss.web.service.impl;

import com.aliyun.oss.OSS;
import com.orchids.aliyunoss.aliyun.AliyunProperties;
import com.orchids.aliyunoss.web.service.FileService;
import lombok.RequiredArgsConstructor;
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;

/**
 * @ Author qwh
 * @ Date 2024/6/27 14:57
 */
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    private final OSS ossClient;

    private final AliyunProperties aliyunProperties;

    @Override
    public String upload(MultipartFile file) {
        try {
            // 上传文件流。
            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(aliyunProperties.getBucketName(), fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //上传之后文件路径
            // https://nullpointer2024.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://" + aliyunProperties.getBucketName() + "." + aliyunProperties.getEndpoint() + "/" + fileName;
            //返回
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
test
相关推荐
未来之窗软件服务6 分钟前
sql速度优化多条合并为一条语句
数据库
山东布谷科技官方8 分钟前
布谷直播源码部署服务器关于数据库配置的详细说明
运维·服务器·数据库·直播系统源码·直播源码·直播系统搭建·直播软件开发
LuckyLay18 分钟前
Spring学习笔记_27——@EnableLoadTimeWeaving
java·spring boot·spring
易云码28 分钟前
信息安全建设方案,网络安全等保测评方案,等保技术解决方案,等保总体实施方案(Word原件)
数据库·物联网·安全·web安全·低代码
newxtc34 分钟前
【客观理性深入讨论国产中间件及数据库-科创基础软件】
数据库·中间件·国产数据库·国产中间件·科创
水月梦镜花36 分钟前
redis:list列表命令和内部编码
数据库·redis·list
佳佳_1 小时前
Spring Boot 应用启动时打印配置类信息
spring boot·后端
MonkeyKing_sunyuhua1 小时前
ubuntu22.04 docker-compose安装postgresql数据库
数据库·docker·postgresql
天郁青1 小时前
数据库交互的本地项目:后台管理系统
数据库·交互
马剑威(威哥爱编程)1 小时前
MongoDB面试专题33道解析
数据库·mongodb·面试