OssBootUtil

package org.jeecg.common.util.oss;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.filter.FileTypeFilter;
import org.jeecg.common.util.filter.StrAttackFilter;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
* @Description: 阿里云 oss 上传工具类(高依赖版)
* @Date: 2019/5/10
*/
@Slf4j
public class OssBootUtil {

private static String endPoint;
private static String accessKeyId;
private static String accessKeySecret;
private static String bucketName;
private static String staticDomain;

public static void setEndPoint(String endPoint) {
OssBootUtil.endPoint = endPoint;
}

public static void setAccessKeyId(String accessKeyId) {
OssBootUtil.accessKeyId = accessKeyId;
}

public static void setAccessKeySecret(String accessKeySecret) {
OssBootUtil.accessKeySecret = accessKeySecret;
}

public static void setBucketName(String bucketName) {
OssBootUtil.bucketName = bucketName;
}

public static void setStaticDomain(String staticDomain) {
OssBootUtil.staticDomain = staticDomain;
}

public static String getStaticDomain() {
return staticDomain;
}

public static String getEndPoint() {
return endPoint;
}

public static String getAccessKeyId() {
return accessKeyId;
}

public static String getAccessKeySecret() {
return accessKeySecret;
}

public static String getBucketName() {
return bucketName;
}

public static OSSClient getOssClient() {
return ossClient;
}

/**
* oss 工具客户端
*/
private static OSSClient ossClient = null;

/**
* 上传文件至阿里云 OSS
* 文件上传成功,返回文件完整访问路径
* 文件上传失败,返回 null
*
* @param file 待上传文件
* @param fileDir 文件保存目录
* @return oss 中的相对文件路径
*/
public static String upload(MultipartFile file, String fileDir, String customBucket) {
String FILE_URL = null;
initOSS(endPoint, accessKeyId, accessKeySecret);
StringBuilder fileUrl = new StringBuilder();
String newBucket = bucketName;
if (oConvertUtils.isNotEmpty(customBucket)) {
newBucket = customBucket;
}
try {
//判断桶是否存在,不存在则创建桶
if (!ossClient.doesBucketExist(newBucket)) {
ossClient.createBucket(newBucket);
}
// 获取文件名
String orgName = file.getOriginalFilename();
if ("" == orgName) {
orgName = file.getName();
}
//update-begin-author:liusq date:20210809 for: 过滤上传文件类型
FileTypeFilter.fileTypeFilter(file);
//update-end-author:liusq date:20210809 for: 过滤上传文件类型
orgName = CommonUtils.getFileName(orgName);
String fileName = orgName.indexOf(".") == -1
? orgName + "_" + System.currentTimeMillis()
: orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
if (!fileDir.endsWith("/")) {
fileDir = fileDir.concat("/");
}
//update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
fileDir = StrAttackFilter.filter(fileDir);
//update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
fileUrl = fileUrl.append(fileDir + fileName);

if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
FILE_URL = staticDomain + "/" + fileUrl;
} else {
FILE_URL = "https://" + newBucket + "." + endPoint + "/" + fileUrl;
}
PutObjectResult result = ossClient.putObject(newBucket, fileUrl.toString(), file.getInputStream());
// 设置权限(公开读)
// ossClient.setBucketAcl(newBucket, CannedAccessControlList.PublicRead);
if (result != null) {
log.info("------OSS文件上传成功------" + fileUrl);
}
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
return FILE_URL;
}

/**
* 获取原始URL
*
* @param url: 原始URL
* @Return: java.lang.String
*/
public static String getOriginalUrl(String url) {
String originalDomain = "https://" + bucketName + "." + endPoint;
if (oConvertUtils.isNotEmpty(staticDomain) && url.indexOf(staticDomain) != -1) {
url = url.replace(staticDomain, originalDomain);
}
return url;
}

/**
* 文件上传
*
* @param file
* @param fileDir
* @return
*/
public static String upload(MultipartFile file, String fileDir) {
return upload(file, fileDir, null);
}

/**
* 上传文件至阿里云 OSS
* 文件上传成功,返回文件完整访问路径
* 文件上传失败,返回 null
*
* @param file 待上传文件
* @param fileDir 文件保存目录
* @return oss 中的相对文件路径
*/
public static String upload(FileItemStream file, String fileDir) {
String FILE_URL = null;
initOSS(endPoint, accessKeyId, accessKeySecret);
StringBuilder fileUrl = new StringBuilder();
try {
String suffix = file.getName().substring(file.getName().lastIndexOf('.'));
String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
if (!fileDir.endsWith("/")) {
fileDir = fileDir.concat("/");
}
fileDir = StrAttackFilter.filter(fileDir);
fileUrl = fileUrl.append(fileDir + fileName);
if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
FILE_URL = staticDomain + "/" + fileUrl;
} else {
FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
}
PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.openStream());
// 设置权限(公开读)
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
if (result != null) {
log.info("------OSS文件上传成功------" + fileUrl);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return FILE_URL;
}

/**
* 删除文件
*
* @param url
*/
public static void deleteUrl(String url) {
deleteUrl(url, null);
}

/**
* 删除文件
*
* @param url
*/
public static void deleteUrl(String url, String bucket) {
String newBucket = bucketName;
if (oConvertUtils.isNotEmpty(bucket)) {
newBucket = bucket;
}
String bucketUrl = "";
if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
bucketUrl = staticDomain + "/";
} else {
bucketUrl = "https://" + newBucket + "." + endPoint + "/";
}
url = url.replace(bucketUrl, "");
ossClient.deleteObject(newBucket, url);
}

/**
* 基于前缀(prefix)批量删除文件
*
* @param prefix
*/
public static void deleteBatch(String prefix) {

// 指定前缀 prefix

// 创建OSSClient实例。
initOSS(endPoint, accessKeyId, accessKeySecret);

try {
// 列举所有包含指定前缀的文件并删除。指定marker(例如exampleobject.txt)之后的文件
String nextMarker = null;
ObjectListing objectListing = null;
do {
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName)
.withPrefix(prefix)
.withMarker(nextMarker);

objectListing = ossClient.listObjects(listObjectsRequest);
if (objectListing.getObjectSummaries().size() > 0) {
List<String> keys = new ArrayList<String>();
for (OSSObjectSummary s : objectListing.getObjectSummaries()) {
System.out.println("key name: " + s.getKey());
keys.add(s.getKey());
}
DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url");
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest);
List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
try {
for (String obj : deletedObjects) {
String deleteObj = URLDecoder.decode(obj, "UTF-8");
System.out.println(deleteObj);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

nextMarker = objectListing.getNextMarker();
} while (objectListing.isTruncated());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
// if (ossClient != null) {
// ossClient.shutdown();
// }
}
}

/**
* 删除文件
*
* @param fileName
*/
public static void delete(String fileName) {
ossClient.deleteObject(bucketName, fileName);
}

/**
* 获取文件流
*
* @param objectName
* @param bucket
* @return
*/
public static InputStream getOssFile(String objectName, String bucket) {
InputStream inputStream = null;
try {
String newBucket = bucketName;
if (oConvertUtils.isNotEmpty(bucket)) {
newBucket = bucket;
}
initOSS(endPoint, accessKeyId, accessKeySecret);
OSSObject ossObject = ossClient.getObject(newBucket, objectName);
inputStream = new BufferedInputStream(ossObject.getObjectContent());
} catch (Exception e) {
log.info("文件获取失败" + e.getMessage());
}
return inputStream;
}

/**
* 获取文件流
*
* @param objectName
* @return
*/
public static InputStream getOssFile(String objectName) {
return getOssFile(objectName, null);
}

/**
* 获取文件外链
*
* @param bucketName
* @param objectName
* @param expires
* @return
*/
public static String getObjectURL(String bucketName, String objectName, Date expires) {
initOSS(endPoint, accessKeyId, accessKeySecret);
try {
if (ossClient.doesObjectExist(bucketName, objectName)) {
URL url = ossClient.generatePresignedUrl(bucketName, objectName, expires);
return URLDecoder.decode(url.toString(), "UTF-8");
}
} catch (Exception e) {
log.info("文件路径获取失败" + e.getMessage());
}
return null;
}

/**
* 初始化 oss 客户端
*
* @return
*/
@Scope("prototype")
private static OSSClient initOSS(String endpoint, String accessKeyId, String accessKeySecret) {
if (ossClient == null) {
ossClient = new OSSClient(endpoint,
new DefaultCredentialProvider(accessKeyId, accessKeySecret),
new ClientConfiguration());
}
return ossClient;
}


/**
* 上传文件到oss
*
* @param stream
* @param relativePath
* @return
*/
public static String upload(InputStream stream, String relativePath) {
String FILE_URL = null;
String fileUrl = relativePath;
initOSS(endPoint, accessKeyId, accessKeySecret);
if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
FILE_URL = staticDomain + "/" + relativePath;
} else {
FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
}
PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), stream);
// 设置权限(公开读)
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
if (result != null) {
log.info("------OSS文件上传成功------" + fileUrl);
}
return FILE_URL;
}


// public static void main(String[] args) {
//
// String str = "http://oss.ziyouzhaofang.com/proapkmanages/123_1649728374212.txt";
//
// String result = str.substring(str.lastIndexOf("http://oss.ziyouzhaofang.com/") + 29);
// //输出结果
// System.out.println(result);
//// copy();
// }

/**
* 拷贝文件
*
* @param strPath
* @param appName
* @return
*/
public static String copy(String strPath, String appName) {

String FILE_URL = null;
// 填写源Bucket名称。
String sourceBucketName = bucketName;
// 填写源Object的完整路径,完整路径中不能包含Bucket名称。
String sourceKey = strPath;
// 填写与源Bucket处于同一地域的目标Bucket名称。
String destinationBucketName = bucketName;
// 填写目标Object的完整路径。Object完整路径中不能包含Bucket名称。
String destinationKey = appName;

initOSS(endPoint, accessKeyId, accessKeySecret);
// initOSS("oss-cn-beijing.aliyuncs.com", "LTAI5tMDGQKQVnwU2MWzde7T", "ZHs6Uxa10f8qkJ5HpqLmf614hoP5VO");

try {
// 拷贝文件。
CopyObjectResult result = ossClient.copyObject(sourceBucketName, sourceKey, destinationBucketName, destinationKey);
System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());
FILE_URL = staticDomain + "/" + appName;
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
// if (ossClient != null) {
// ossClient.shutdown();
// }
}
return FILE_URL;

}


}
posted @ 2022-04-20 15:26  韩憨  阅读(122)  评论(0编辑  收藏  举报
//看板娘