阿里云OSS文件上传工具类,在实际工作中能够正常运用
maven依赖:
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.0</version>
</dependency>
代码如下:
public class AliyunOSSClientUtil {
// log日志
private static Logger logger = LoggerFactory.getLogger(AliyunOSSClientUtil.class);
//oss客户端连接
private static OSS ossclient = null;
/**
* 获得阿里云OSS客户端对象
* 备注:阿里云OSS SDK中提供了自动重连的功能,以确保应用程序在遇到网络问题时仍能与OSS有效通信。
*
* @param ossEndpoint
* @param accessId
* @param accessKey
* @return
*/
public static OSS getOssClient(String ossEndpoint, String accessId, String accessKey) {
if (ossclient == null) {
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
// 设置OSSClient允许打开的最大HTTP连接数,默认为1024个。
conf.setMaxConnections(500);
// 设置Socket层传输数据的超时时间,默认为50000毫秒。
conf.setSocketTimeout(10000);
// 设置建立连接的超时时间,默认为50000毫秒。
conf.setConnectionTimeout(10000);
// 设置从连接池中获取连接的超时时间(单位:毫秒),默认不超时。
conf.setConnectionRequestTimeout(10000);
// 设置连接空闲超时时间。超时则关闭连接,默认为60000毫秒。
conf.setIdleConnectionTime(10000);
// 设置失败请求重试次数,默认为3次。
conf.setMaxErrorRetry(5);
ossclient = new OSSClientBuilder().build(ossEndpoint,accessId,accessKey,conf);
}
return ossclient;
}
/**
* 创建存储空间
*
* @param ossClient OSS连接
* @param bucketName 存储空间
* @return
*/
public static String createBucketName(OSS ossClient, String bucketName) {
// 存储空间
final String bucketNames = bucketName;
if (!ossClient.doesBucketExist(bucketName)) {
// 创建存储空间
Bucket bucket = ossClient.createBucket(bucketName);
logger.info("创建存储空间成功");
return bucket.getName();
}
return bucketNames;
}
/**
* 删除存储空间bucketName
*
* @param ossClient oss对象
* @param bucketName 存储空间
*/
public static void deleteBucket(OSS ossClient, String bucketName) {
ossClient.deleteBucket(bucketName);
logger.info("删除" + bucketName + "Bucket成功");
}
/**
* 创建模拟文件夹:多级目录
*
* @param ossClient oss连接
* @param bucketName 存储空间
* @param folder 模拟文件夹名如"upload/2023/01/11/"
* @return 文件夹名
*/
public static String createFolder(OSS ossClient, String bucketName, String folder) {
// 文件夹名
final String keySuffixWithSlash = folder;
// 判断文件夹是否存在,不存在则创建
if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
// 创建文件夹
ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
logger.info("创建文件夹成功");
// 得到文件夹名
OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
String fileDir = object.getKey();
return fileDir;
}
return keySuffixWithSlash;
}
/**
* 根据key删除OSS服务器上的文件
*
* @param ossClient oss连接
* @param bucketName 存储空间
* @param key Bucket下的文件的路径名+文件名 如:"upload/2023/01/11/cake.jpg"
*/
public static void deleteObject(OSS ossClient, String bucketName, String key) {
ossClient.deleteObject(bucketName, key);
logger.info("删除" + bucketName + "下的文件" + key + "成功");
}
/**
* 上传文件
*
* @param ossClient oss连接
* @param bucketName 存储空间
* @param ossPath 上传文件相对路径+文件名如"upload/2023/01/11/cake.jpg"
* @param is 以输入流的形式上传文件
* @param fileName 上传文件后新文件名
* @return String 返回的唯一MD5数字签名
*/
public static String uploadFileOss(OSS ossClient, String bucketName, String ossPath, InputStream is, String fileName) {
try {
// 文件大小
long fileSize = is.available();
// 创建上传Object的Metadata
ObjectMetadata metadata = new ObjectMetadata();
// 上传的文件的长度
metadata.setContentLength(is.available());
// 指定该Object被下载时的网页的缓存行为
metadata.setCacheControl("no-cache");
// 指定该Object下设置Header
metadata.setHeader("Pragma", "no-cache");
// 指定该Object被下载时的内容编码格式
metadata.setContentEncoding("utf-8");
// 文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
// 如果没有扩展名则填默认值application/octet-stream
metadata.setContentType(getContentType(fileName));
// 指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte");
//上传文件到OSS时需要指定包含文件后缀在内的完整路径如ossPath="upload/2023/01/11/cake.jpg"
PutObjectResult putResult = ossClient.putObject(bucketName, ossPath, is, metadata);
// 解析结果
String resultStr = putResult.getETag();
logger.info("唯一MD5数字签名:" + resultStr);
//上传文件后相对路径如"upload/2023/01/11/cake.jpg"
String path = ossPath;
return path;
} catch (Exception e) {
e.printStackTrace();
logger.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
return null;
}
}
/**
* 下载文件到本地
*
* @param ossClient oss连接
* @param bucketName 存储空间
* @param key Bucket下的文件的路径名+文件名 如:"upload/2023/01/11/cake.jpg"
* @param localFilePath 下载本地文件绝对路径如"C:\Users\Administrator\Desktop\oss-download\xxx.pdf"
*/
public static void downloadFileOss(OSS ossClient, String bucketName, String key, String localFilePath) {
try {
//创建本地文件
File file = new File(localFilePath);
GetObjectRequest objectRequest = new GetObjectRequest(bucketName, key);
//下载OSS文件到本地文件,若指定的本地文件存在则覆盖,否则新建
ossClient.getObject(objectRequest, file);
logger.info("下载文件到本地成功");
} catch (OSSException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
/**
* 获取上传文件对象
* 备注:最重要的是获取上传文件的输出流InputStream
*
* @param ossClient oss连接
* @param bucketName 存储空间
* @param key Bucket下的文件的路径名+文件名 如:"upload/2023/01/11/cake.jpg"
* @return
*/
public static OSSObject getObject(OSS ossClient, String bucketName, String key) {
OSSObject object = null;
try {
object = ossClient.getObject(bucketName, key);
//文件大小
long fileSize = object.getObjectMetadata().getContentLength();
//文件相对路径
String ossPath = object.getKey();
//文件输入流
InputStream is = object.getObjectContent();
logger.info("success to getObject,fileSize:" + fileSize + "\nossPath:" + ossPath + "\ninputStream:" + is);
} catch (OSSException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
return object;
}
/**
* 获取上传文件url
*
* @param ossClient
* @param bucketName
* @param key
* @return
*/
public static String getUrl(OSS ossClient, String bucketName, String key) {
//设置URl过期时间为99年:3600L*1000*24*365*99
Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 99);
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key);
generatePresignedUrlRequest.setExpiration(expiration);
URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
String returnUrl = url.toString();
return returnUrl;
}
/**
* 通过文件名判断并获取OSS服务文件上传时文件的contentType
*
* @param fileName 文件名
* @return 文件的contentType
*/
public static String getContentType(String fileName) {
// 文件的后缀名
String fileExtension = fileName.substring(fileName.lastIndexOf("."));
logger.info("getContentType->fileName={},fileExtension={}", fileName, fileExtension);
for (AliyunOssFileTypeEnum e : AliyunOssFileTypeEnum.values()) {
if (e.getCode().equalsIgnoreCase(fileExtension)) {
return e.getText();
}
}
// 默认返回类型
return AliyunOssFileTypeEnum.TXT.getText();
}
// 测试
public static void main(String[] args) throws FileNotFoundException {
//阿里云OSS账号自行到阿里云官网申请
String ossEndpoint = "XXX";
String accessId = "XXX";
String accessKey = "XXX";
String bucketName = "test";
// 初始化OSSClient
OSS ossClient = AliyunOSSClientUtil.getOssClient(ossEndpoint, accessId, accessKey);
//测试创建多级目录
/*String tmpDir = "upload/2023/01/11/";
String folder = createFolder(ossClient, bucketName, tmpDir);
System.out.println("folder:"+folder);*/
//测试删除文件
/*String key="upload/2023/01/11/xxx.pdf";
deleteObject(ossClient,bucketName,key);*/
//测试上传文件
/*String pathAndname = "C:\\Users\\Administrator\\Desktop\\测试文件上传\\xxx.pdf";
File file = new File(pathAndname);
//原始文件名:带后缀
String oldfilename = file.getName();
//新文件名:带后缀
String newfilename = "9065df0f3ab72419b36d2dec088e11d6.pdf";//可以自行生成随机唯一文件名
String newpath = "C:\\Users\\Administrator\\Desktop\\upload\\2023\\01\\11\\";
String ossPath = newpath + newfilename;
InputStream is = new FileInputStream(file);
String absolutePath = uploadFileOss(ossClient, bucketName, ossPath, is, newfilename);
System.out.println("absolutePath:"+absolutePath);*/
//测试获取文件url
/*String key="upload/2023/01/11/9065df0f3ab72419b36d2dec088e11d6.pdf";
String url = getUrl(ossClient, bucketName, key);
System.out.println("url:"+url);*/
//测试获取上传对象
/*String key = "upload/2023/01/11/9065df0f3ab72419b36d2dec088e11d6.pdf";
getObject(ossClient, bucketName, key);*/
//测试下载文件到本地
/*String key = "upload/2023/01/11/9065df0f3ab72419b36d2dec088e11d6.pdf";
String localFilePath = "C:\\Users\\Administrator\\Desktop\\oss-download\\xxx.pdf";
downloadFileOss(ossClient, bucketName, key, localFilePath);*/
}
文件类型枚举值:
public enum AliyunOssFileTypeEnum {
BMP(".bmp","image/bmp"),
GIF(".gif","image/gif"),
JPEG(".jpeg","image/jpeg"),
JPG(".jpg","image/jpeg"),
PNG(".png","image/jpeg"),
HTML(".html","text/html"),
XML(".xml","text/xml"),
TXT(".txt","application/octet-stream"),
SQL(".sql","application/octet-stream"),
VSD(".vsd","application/vnd.visio"),
PDF(".pdf","application/pdf"),
PPT(".ppt","application/vnd.ms-powerpoint"),
PPTX(".pptx","application/vnd.ms-powerpoint"),
DOC(".doc","application/msword"),
DOCX(".docx","application/msword"),
XLS(".xls","application/vnd.ms-excel"),
XLSX(".xlsx","application/vnd.ms-excel"),
CSV(".csv","application/vnd.ms-excel");
String code;
String text;
AliyunOssFileTypeEnum() {
}
AliyunOssFileTypeEnum(String code, String text) {
this.code = code;
this.text = text;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}