springboot阿里云oss工具类
pom依赖;
yml配置:
读取配置文件类:
上传:
完整工具类代码:
点击查看代码
`
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.luzhizheng.common.config.OSSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Sappy
* @date 4/6/2023 10:40:44
*/
@Component
public class AliYunOSSUtil {
@Autowired
private OSSConfig ossConfig;
private static String FOLDER = "文件夹";
/**
* 本地文件上传到oss
* @param file
* @return
* @throws FileNotFoundException
*/
public String upload(File file) throws FileNotFoundException {
String absolutePath = file.getAbsolutePath();
String fileName = file.getName();
FileInputStream is = new FileInputStream(absolutePath);
ObjectMetadata metadata = new ObjectMetadata();
int indexOfLastDot = fileName.lastIndexOf(".");
String suffix = fileName.substring(indexOfLastDot);
metadata.setContentType(getContentType(suffix));
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
fileName = uuid + suffix;
String datePath = DateTimeFormatter.ISO_DATE.format(LocalDate.now());
fileName = FOLDER + "/" + datePath + "/" + fileName;
PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucket(), fileName, is);
//设置ContentType,预览
putObjectRequest.setMetadata(metadata);
OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
ossClient.putObject(putObjectRequest);
/* //临时第三方授权
Date expiration = new Date(System.currentTimeMillis() + 3600000L * 24);
URL url = ossClient.generatePresignedUrl(ossConfig.getBucket(), aimFilePathName, expiration);*/
String url = "https://" + ossConfig.getBucket() + "." + ossConfig.getEndpoint() + "/" + fileName;
// 关闭ossClient
ossClient.shutdown();
return url;
}
/**
* multipartFile上传到oss
* @param multipartFile
* @return
* @throws IOException
*/
public String upload(MultipartFile multipartFile) throws IOException {
InputStream inputStream = multipartFile.getInputStream();
String fileName = multipartFile.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
fileName = uuid + fileName;
String datePath = DateTimeFormatter.ISO_DATE.format(LocalDate.now());
// 拼接fileName , 文件夹1/文件夹2/文件名.jpg
fileName = FOLDER + "/" + datePath + "/" + fileName;
// 如果需要上传时设置存储类型与访问权限
ObjectMetadata metadata = new ObjectMetadata();
int indexOfLastDot = fileName.lastIndexOf(".");
String suffix = fileName.substring(indexOfLastDot);
metadata.setContentType(getContentType(suffix));
PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucket(), fileName, inputStream);
//设置ContentType,预览
putObjectRequest.setMetadata(metadata);
OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
ossClient.putObject(putObjectRequest);
/* //临时第三方授权
Date expiration = new Date(System.currentTimeMillis() + 3600000L * 24);
URL url = ossClient.generatePresignedUrl(ossConfig.getBucket(), aimFilePathName, expiration);*/
String url = "https://" + ossConfig.getBucket() + "." + ossConfig.getEndpoint() + "/" + fileName;
ossClient.shutdown();
return url;
}
private static String getContentType(String suffix) {
if (suffix.equalsIgnoreCase(".bmp")) {
return "image/bmp";
}
if (suffix.equalsIgnoreCase(".gif")) {
return "image/gif";
}
if (suffix.equalsIgnoreCase(".jpeg") ||
suffix.equalsIgnoreCase(".jpg") ||
suffix.equalsIgnoreCase(".png")
) {
return "image/jpg";
}
return "image/jpg";
}
/**
* 列举 指定路径下所有的文件的文件名
* 如果要列出根路径下的所有文件,path= ""
*
* @param path
* @return
*/
public List<String> listFileName(String path) {
// 构造ListObjectsRequest请求。
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(ossConfig.getBucket());
// 设置prefix参数来获取path目录下的所有文件。
listObjectsRequest.setPrefix(path);
OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
// 列出文件。
ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
List<OSSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
List<String> list = objectSummaries.stream().map(OSSObjectSummary::getKey).collect(Collectors.toList());
ossClient.shutdown();
return list;
}
/**
* 列举文件下所有的文件url信息
*/
public List<String> listFileUrl(String path) {
List<String> res = new ArrayList<>();
// 构造ListObjectsRequest请求
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(ossConfig.getBucket());
// 设置prefix参数来获取fun目录下的所有文件。
listObjectsRequest.setPrefix(path);
OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
// 列出文件。
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(ossConfig.getBucket(), objectSummary.getKey(), expiration);
res.add(url.toString());
}
// 关闭OSSClient。
ossClient.shutdown();
return res;
}
/**
* 判断文件是否存在
*
* @param objectName
* @return
*/
public boolean isFileExist(String objectName) {
OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
return ossClient.doesObjectExist(ossConfig.getBucket(), objectName);
}
/**
* 通过文件名下载文件
*
* @param ossFileName 要下载的文件名
* @param localFileName 本地要创建的文件名
*/
public void downloadFile(String ossFileName, String localFileName) {
OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
// 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
ossClient.getObject(new GetObjectRequest(ossConfig.getBucket(), ossFileName), new File(localFileName));
// 关闭OSSClient。
ossClient.shutdown();
}
/**
* 删除文件或目录
*
* @param objectName
*/
public void deleteFile(String objectName) {
OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
ossClient.deleteObject(ossConfig.getBucket(), objectName);
ossClient.shutdown();
}
/**
* 批量删除文件或目录
*
* @param keys
*/
public void deleteFiles(List<String> keys) {
OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
// 删除文件。
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(ossConfig.getBucket()).withKeys(keys));
deleteObjectsResult.getDeletedObjects();
ossClient.shutdown();
}
/**
* 创建文件夹
*
* @param folder
* @return
*/
public String createFolder(String folder) {
// 文件夹名
final String keySuffixWithSlash = folder;
OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
// 判断文件夹是否存在,不存在则创建
if (!ossClient.doesObjectExist(ossConfig.getBucket(), keySuffixWithSlash)) {
// 创建文件夹
ossClient.putObject(ossConfig.getBucket(), keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
// 得到文件夹名
OSSObject object = ossClient.getObject(ossConfig.getBucket(), keySuffixWithSlash);
String fileDir = object.getKey();
ossClient.shutdown();
return fileDir;
}
return keySuffixWithSlash;
}
}