依赖
<!-- 阿里云OSS -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.14.0</version>
</dependency>
<!-- 非阿里云相关的依赖 -->
<!-- 单元测试Junit -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
配置信息类
import lombok.Data;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
@Data
public class AliOSSConfig {
/**
* 存储区域
* 例:oss-cn-shanghai.aliyuncs.com
*/
private String endpoint;
/**
* KeyId
*/
private String accessKeyId;
/**
* KeySecret
*/
private String accessKeySecret;
/**
* bucket存储空间名称
*/
private String bucketName;
private AliOSSConfig() {
Properties properties = new Properties();
try {
InputStream is = AliOSSConfig.class.getResourceAsStream("/alioss.properties");
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
endpoint = properties.getProperty("endpoint");
accessKeyId = properties.getProperty("accessKeyId");
accessKeySecret = properties.getProperty("accessKeySecret");
bucketName = properties.getProperty("bucketName");
}
private static AliOSSConfig instance = new AliOSSConfig();
public static AliOSSConfig getInstance() {
return instance;
}
public static void main(String[] args) {
AliOSSConfig oss = new AliOSSConfig();
System.out.println(oss.endpoint);
System.out.println(oss.accessKeyId);
System.out.println(oss.accessKeySecret);
System.out.println(oss.bucketName);
}
}
配置文件
#存储区域 例:oss-cn-shanghai.aliyuncs.com
endpoint=***
accessKeyId=***
accessKeySecret=***
#bucket存储空间名称
bucketName=***
工具类
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.mall.config.AliOSSConfig;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;
public class AliOSSUtil {
private static final String endpoint = AliOSSConfig.getInstance().getEndpoint();
private static final String accessKeyId = AliOSSConfig.getInstance().getAccessKeyId();
private static final String accessKeySecret = AliOSSConfig.getInstance().getAccessKeySecret();
private static final String bucketName = AliOSSConfig.getInstance().getBucketName();
/**
* 针对MultipartFile类型
*
* @param multipartFile 前端传回的MultipartFile类型的数据
* @return java.lang.String 返回该文件的访问链接
*/
public static String upload(MultipartFile multipartFile) throws IOException {
// 获取上传的文件的输入流
InputStream inputStream = multipartFile.getInputStream();
// 获取文件名称
String fileName = multipartFile.getOriginalFilename();
// 避免文件覆盖
int i = fileName.lastIndexOf(".");
String suffix = fileName.substring(i);
fileName = fileName.substring(0, i) + "_" + System.currentTimeMillis() + suffix;
return upload(inputStream, fileName);
}
/**
* 针对Base64类型
*
* @param base64 Base64字符串,标准的Base64字符串,例如data:image/png;base64,iVBORw0...
* @return java.lang.String 返回该文件的访问链接
*/
public static String upload(String base64) {
// 获取上传的文件的输入流
byte[] bytes = Base64.getDecoder().decode(base64.split(",")[1]);
InputStream inputStream = new ByteArrayInputStream(bytes);
// 获取文件名称
String fileName = base64.substring(base64.indexOf(":") + 1, base64.indexOf(";")).replace("/", ".");
return upload(inputStream, fileName);
}
/**
* 查询所有文件名称
*
* @param path 相对于阿里云bucket存储空间的文件路径
* @return java.util.List<java.lang.String> 该路径下所有文件的名称
* <p>
* 注:首先会获取根文件的名称
*/
public static List<String> listFileName(String path) {
List<String> res = new ArrayList<>();
// 构造ListObjectsRequest请求。
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
// 设置prefix参数来获取fun目录下的所有文件。
listObjectsRequest.setPrefix(path);
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 列出文件。
ObjectListing listing = ossClient.listObjects(listObjectsRequest);
// 遍历所有文件
for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
System.out.println(objectSummary.getKey());
}
// 关闭OSSClient。
ossClient.shutdown();
return res;
}
/**
* 查询所有文件的url
*
* @param path 相对于阿里云bucket存储空间的文件路径
* @return java.util.List<java.lang.String> 返回路径下所有文件的url
* <p>
* 注:首先会获取根文件夹的url,且根文件夹的url无法访问
*/
public static List<String> listFileUrl(String path) {
List<String> res = new ArrayList<>();
// 构造ListObjectsRequest请求
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
// 设置prefix参数来获取fun目录下的所有文件。
listObjectsRequest.setPrefix(path);
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 列出文件。
ObjectListing listing = ossClient.listObjects(listObjectsRequest);
// 遍历所有文件。
for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
//文件访问路径
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
URL url = ossClient.generatePresignedUrl(bucketName, objectSummary.getKey(), expiration);
res.add(url.toString());
}
// 关闭OSSClient。
ossClient.shutdown();
return res;
}
/**
* 判断文件是否存在
*
* @param objectName 相对于阿里云bucket存储空间的文件路径和文件名称
* @return boolean 存在返回true,存在返回false
*/
public static boolean isFileExist(String objectName) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
boolean res = ossClient.doesObjectExist(bucketName, objectName);
return res;
}
/**
* 通过文件名称(包括路径)下载文件
*
* @param objectName 相对于阿里云bucket存储空间的文件路径和文件名称
* @param localFileName 下载的路径和文件名称
*/
public static void downloadFile(String objectName, String localFileName) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFileName));
// 关闭OSSClient。
ossClient.shutdown();
}
/**
* 删除文件或目录
*
* @param objectName 相对于阿里云bucket存储空间的文件路径和文件名称
*/
public static void deleteFile(String objectName) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ossClient.deleteObject(bucketName, objectName);
ossClient.shutdown();
}
/**
* 批量删除文件或目录
*
* @param keys 相对于阿里云bucket存储空间的文件路径和文件名称
*/
public static void deleteFiles(List<String> keys) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 删除文件。
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
java.util.List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
ossClient.shutdown();
}
/**
* 创建文件夹
*
* @param folder 文件夹名称。注:文件夹名称后面需要添加“/”,否则创建的是文件,并非文件夹。
* @return java.lang.String 相对于阿里云bucket存储空间的文件夹路径
*/
public static String createFolder(String folder) {
// 文件夹名
final String keySuffixWithSlash = folder;
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 判断文件夹是否存在,不存在则创建
if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
// 创建文件夹
ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
// 得到文件夹名
OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
String fileDir = object.getKey();
ossClient.shutdown();
return fileDir;
}
return keySuffixWithSlash;
}
/**
* 文件上传,文件上传后会将文件放置在当前日期的目录中,如:2022-07-08/1_1657251247153.png
*
* @param inputStream 上传文件的流
* @param fileName 文件名称,命名规则是:文件名+当前时间戳+后缀
* @return java.lang.String 返回该文件的访问链接
*/
private static String upload(InputStream inputStream, String fileName) {
// 避免文件被覆盖,为上传文件名称添加时间戳
int i = fileName.lastIndexOf(".");
String suffix = fileName.substring(i);
fileName = fileName.substring(0, i) + "_" + System.currentTimeMillis() + suffix;
// 把文件按照日期进行分类
// 获取当前日期
String datePath = DateTimeFormatter.ISO_DATE.format(LocalDate.now());
// 拼接fileName
fileName = datePath + "/" + fileName;
// 如果需要上传时设置存储类型与访问权限
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
// 上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
putObjectRequest.setMetadata(metadata);
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ossClient.putObject(putObjectRequest);
//文件访问路径
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
// 关闭ossClient
ossClient.shutdown();
// 把上传到oss的路径返回
return url.toString();
}
private static String getContentType(String FileNameExtension) {
if (FileNameExtension.equalsIgnoreCase(".bmp")) {
return "image/bmp";
}
if (FileNameExtension.equalsIgnoreCase(".gif")) {
return "image/gif";
}
if (FileNameExtension.equalsIgnoreCase(".jpeg") ||
FileNameExtension.equalsIgnoreCase(".jpg") ||
FileNameExtension.equalsIgnoreCase(".png")
) {
return "image/jpg";
}
return "image/jpg";
}
}
测试
import org.junit.jupiter.api.Test;
import java.io.FileNotFoundException;
import java.util.List;
class AliOSSUtilTest {
@Test
void listFileName() {
List<String> res = AliOSSUtil.listFileName("test/");
res.forEach(System.out::println);
}
@Test
void listFileUrl() {
List<String> res = AliOSSUtil.listFileUrl("test/");
res.forEach(System.out::println);
}
@Test
void isFileExist() {
boolean res = AliOSSUtil.isFileExist("test/K1650520204753.jpg");
System.out.println(res);
}
@Test
void downloadFile() {
AliOSSUtil.downloadFile("test/K1650520204753.jpg", "d:/KK.jpg");
}
@Test
void delelteFile() {
AliOSSUtil.delelteFile("test/KK1650521987347.jpg");
}
@Test
void deleteFiles() {
List<String> keys = List.of("KK1650522195064.jpg", "KK1650522206716.jpg");
AliOSSUtil.deleteFiles(keys);
}
@Test
void createFolder() {
String folder = AliOSSUtil.createFolder("test2/");
System.out.println(folder);
}
}