引入依赖
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;
}
}
}