给一个阿里云oss的工具类
时间: 2024-06-09 17:09:59 浏览: 190
这里提供一个 Java 版本的阿里云 OSS 工具类,方便上传、下载、删除等操作。
```java
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;
/**
* 阿里云 OSS 工具类
*/
public class AliyunOSSUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(AliyunOSSUtil.class);
private static OSS ossClient;
/**
* 初始化 OSS 客户端
*
* @param endpoint OSS 服务的 endpoint
* @param accessKeyId 访问 OSS 服务的 accessKeyId
* @param accessKeySecret 访问 OSS 服务的 accessKeySecret
*/
public static void initOSSClient(String endpoint, String accessKeyId, String accessKeySecret) {
ClientConfiguration config = new ClientConfiguration();
config.setConnectionTimeout(5000); // 设置连接超时时间,默认50000毫秒
config.setMaxErrorRetry(3); // 设置请求失败后最大重试次数,默认3次
ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, config);
}
/**
* 销毁 OSS 客户端
*/
public static void destroyOSSClient() {
if (ossClient != null) {
ossClient.shutdown();
}
}
/**
* 上传文件到 OSS
*
* @param bucketName OSS bucket 名称
* @param filePath 本地文件路径
* @param objectName OSS 上的文件名称
* @return 文件 URL
*/
public static String uploadFile(String bucketName, String filePath, String objectName) {
try {
// 创建 PutObjectRequest 对象
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
// 如果需要上传时设置存储类型与访问权限,请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
// 上传文件
ossClient.putObject(putObjectRequest);
// 获取文件 URL
Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000); // 设置 URL 过期时间为 1 小时
URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
LOGGER.info("Upload file to OSS success, object name: {}, URL: {}", objectName, url);
return url.toString();
} catch (Exception e) {
LOGGER.error("Upload file to OSS failed, object name: {}", objectName, e);
return null;
}
}
/**
* 下载 OSS 上的文件
*
* @param bucketName OSS bucket 名称
* @param objectName OSS 上的文件名称
* @param localPath 本地存储路径
*/
public static void downloadFile(String bucketName, String objectName, String localPath) {
try {
// 下载文件
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
InputStream inputStream = ossObject.getObjectContent();
OutputStream outputStream = new FileOutputStream(localPath);
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.close();
inputStream.close();
LOGGER.info("Download file from OSS success, object name: {}, local path: {}", objectName, localPath);
} catch (Exception e) {
LOGGER.error("Download file from OSS failed, object name: {}", objectName, e);
}
}
/**
* 判断 OSS 上是否存在指定文件
*
* @param bucketName OSS bucket 名称
* @param objectName OSS 上的文件名称
* @return true:存在,false:不存在
*/
public static boolean isExist(String bucketName, String objectName) {
try {
return ossClient.doesObjectExist(bucketName, objectName);
} catch (Exception e) {
LOGGER.error("Check object exist failed, object name: {}", objectName, e);
return false;
}
}
/**
* 删除 OSS 上的文件
*
* @param bucketName OSS bucket 名称
* @param objectName OSS 上的文件名称
*/
public static void deleteFile(String bucketName, String objectName) {
try {
ossClient.deleteObject(bucketName, objectName);
LOGGER.info("Delete file from OSS success, object name: {}", objectName);
} catch (Exception e) {
LOGGER.error("Delete file from OSS failed, object name: {}", objectName, e);
}
}
/**
* 列举 OSS bucket 中的所有文件
*
* @param bucketName OSS bucket 名称
* @return 文件列表
*/
public static List<OSSObjectSummary> listObjects(String bucketName) {
try {
ObjectListing objectListing = ossClient.listObjects(bucketName);
return objectListing.getObjectSummaries();
} catch (Exception e) {
LOGGER.error("List objects failed, bucket name: {}", bucketName, e);
return null;
}
}
}
```
使用方法:
```java
// 初始化 OSS 客户端
AliyunOSSUtil.initOSSClient("your endpoint", "your accessKeyId", "your accessKeySecret");
// 上传文件
String fileUrl = AliyunOSSUtil.uploadFile("your bucket name", "your local file path", "your object name");
// 下载文件
AliyunOSSUtil.downloadFile("your bucket name", "your object name", "your local path");
// 判断文件是否存在
boolean isExist = AliyunOSSUtil.isExist("your bucket name", "your object name");
// 删除文件
AliyunOSSUtil.deleteFile("your bucket name", "your object name");
// 列举 bucket 中的所有文件
List<OSSObjectSummary> objectSummaries = AliyunOSSUtil.listObjects("your bucket name");
// 销毁 OSS 客户端
AliyunOSSUtil.destroyOSSClient();
```
阅读全文