一、pom.xml依赖
<dependency>
<groupId>com.huaweicloud</groupId>
<artifactId>esdk-obs-java-bundle</artifactId>
<version>3.21.12</version>
</dependency>
二、配置文件
##华为OBS接入配置
huaweiobs:
#OBS服务所在地址
endPoint: https://xxx
#存储桶名称
bucketName: bucket-test
#访问的key
ak: xxx
#访问的秘钥
sk: xxx
三、配置类
package com.xxx.config;
import com.xxx.util.HuaWeiOBSUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HuaWeiOBSConfig {
@Value("${huaweiobs.bucketName:bucketNameCfg}")
private String bucketName;
@Value("${huaweiobs.ak:akCfg}")
private String ak;
@Value("${huaweiobs.sk:skCfg}")
private String sk;
@Value("${huaweiobs.endPoint:endPointCfg}")
private String endPoint;
@Bean
public HuaWeiOBSUtil huaWeiOBSUtil() {
return new HuaWeiOBSUtil(bucketName, ak, sk, endPoint);
}
}
四、工具类
package com.xxx.util;
import com.obs.services.ObsClient;
import com.obs.services.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class HuaWeiOBSUtil {
private static long expire = 7 * 24 * 60 * 60;
private static String port = ":443";
private static String bucketName;
private static String ak;
private static String sk;
private static String endPoint;
private static ObsClient obsClient = null;
private static final String SEPARATOR = "/";
public HuaWeiOBSUtil(String bucketName, String ak, String sk, String endPoint) {
HuaWeiOBSUtil.bucketName = bucketName;
HuaWeiOBSUtil.ak = ak;
HuaWeiOBSUtil.sk = sk;
HuaWeiOBSUtil.endPoint = endPoint;
createObsClientInstance();
}
public static String getBucketName() {
return bucketName;
}
public static String getAk() {
return ak;
}
public static String getSk() {
return sk;
}
public static String getEndPoint() {
return endPoint;
}
private static void createObsClientInstance() {
try {
if (obsClient == null) {
synchronized (ObsClient.class) {
if (obsClient == null) {
obsClient = new ObsClient(ak, sk, endPoint);
}
}
}
createBucket(bucketName, endPoint);
} catch (Exception e) {
log.error("连接华为云存储服务器异常:" + e.getMessage(), e);
}
}
public static String getBasisUrl() {
return getHttpProtocol(endPoint) + "://" + bucketName + "." + endPoint.replace(getHttpProtocol(endPoint) + "://", "") + port + SEPARATOR;
}
public static String getBasisUrl(String bucketName) {
return getHttpProtocol(endPoint) + "://" + bucketName + "." + endPoint.replace(getHttpProtocol(endPoint) + "://", "") + port + SEPARATOR;
}
public static String getRegion(String endPoint) {
String substring = endPoint.substring(endPoint.indexOf(".") + 1);
return substring.substring(0, substring.indexOf("."));
}
public static String getHttpProtocol(String endPoint) {
return endPoint.substring(0, endPoint.indexOf(":"));
}
public static void createBucket(String bucketName, String endPoint) {
if (!headBucket(bucketName)) {
CreateBucketRequest request = new CreateBucketRequest();
request.setBucketName(bucketName);
request.setLocation(getRegion(endPoint));
obsClient.createBucket(request);
}
}
public static HeaderResponse deleteBucket(String bucketName) {
return obsClient.deleteBucket(bucketName);
}
public static boolean headBucket(String bucketName) {
return obsClient.headBucket(bucketName);
}
public static PutObjectResult putObjectByStr(String bucketName, String objectName, String content) {
if (StringUtils.isBlank(content)) {
return null;
}
objectName = buildObjectName(objectName);
return obsClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
}
public static PutObjectResult putObjectByInput(String bucketName, String objectName, InputStream inputStream) {
objectName = buildObjectName(objectName);
return obsClient.putObject(bucketName, objectName, inputStream);
}
public static PutObjectResult putObjectByFileInput(String bucketName, String objectName, FileInputStream fileInputStream) {
objectName = buildObjectName(objectName);
return obsClient.putObject(bucketName, objectName, fileInputStream);
}
public static PutObjectResult putObjectByMultipartFile(String bucketName, String objectName, MultipartFile media) throws IOException {
objectName = buildObjectName(objectName);
return obsClient.putObject(bucketName, objectName, media.getInputStream());
}
public static PutObjectResult putObjectByFile(String bucketName, String objectName, File file) {
objectName = buildObjectName(objectName);
return obsClient.putObject(bucketName, objectName, file);
}
public static boolean downloadObject(String bucketName, String objectName, String filePath) throws Exception {
if (StringUtils.isBlank(filePath)) {
return false;
}
objectName = buildObjectName(objectName);
filePath = filePath.replace("\\", SEPARATOR);
InputStream input = null;
FileOutputStream fileOutputStream = null;
try {
ObsObject obsObject = obsClient.getObject(bucketName, objectName);
input = obsObject.getObjectContent();
if (input == null) {
return false;
}
if (filePath.contains(SEPARATOR)) {
String dir = filePath.substring(0, filePath.lastIndexOf(SEPARATOR));
File difFile = new File(dir);
if (!difFile.exists()) {
boolean mkdirs = difFile.mkdirs();
}
}
File file = new File(filePath);
fileOutputStream = new FileOutputStream(file);
byte[] b = new byte[1024];
int len;
while ((len = input.read(b)) != -1) {
fileOutputStream.write(b, 0, len);
}
return true;
} finally {
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (input != null) {
input.close();
}
}
}
public static String getObjectContent(String bucketName, String objectName) throws IOException {
objectName = buildObjectName(objectName);
InputStream input = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObsObject obsObject = obsClient.getObject(bucketName, objectName);
input = obsObject.getObjectContent();
byte[] b = new byte[1024];
int len;
while ((len = input.read(b)) != -1) {
bos.write(b, 0, len);
}
return new String(bos.toByteArray());
} finally {
bos.close();
if (input != null) {
input.close();
}
}
}
public static InputStream getObject(String bucketName, String objectName) {
objectName = buildObjectName(objectName);
return obsClient.getObject(bucketName, objectName).getObjectContent();
}
public static List<ObsObject> listObjects(String bucketName, String prefix, Integer maxKeys) {
prefix = prefix.startsWith("/") ? prefix.substring(1) : prefix;
ListObjectsRequest request = new ListObjectsRequest(bucketName);
request.setMaxKeys(maxKeys);
request.setPrefix(prefix);
ObjectListing result = obsClient.listObjects(request);
return result.getObjects();
}
public static List<ObsObject> listAllObjects(String bucketName, String prefix) {
prefix = prefix.startsWith("/") ? prefix.substring(1) : prefix;
List<ObsObject> list = new ArrayList<>();
ListObjectsRequest request = new ListObjectsRequest(bucketName);
request.setMaxKeys(1000);
request.setPrefix(prefix);
ObjectListing result;
do {
result = obsClient.listObjects(request);
request.setMarker(result.getNextMarker());
list.addAll(result.getObjects());
} while (result.isTruncated());
return list;
}
public static DeleteObjectResult deleteObject(String bucketName, String objectName) {
objectName = buildObjectName(objectName);
return obsClient.deleteObject(bucketName, objectName);
}
public static CopyObjectResult copyObject(String sourceBucketName, String sourceObjectName,
String destBucketName, String destObjectName) {
return obsClient.copyObject(sourceBucketName, sourceObjectName, destBucketName, destObjectName);
}
public static boolean doesObjectExist(String bucketName, String objectName) {
objectName = buildObjectName(objectName);
return obsClient.doesObjectExist(bucketName, objectName);
}
public static String getSignedUrl(String bucketName, String objectName, Long expires) {
objectName = buildObjectName(objectName);
TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, expires);
request.setBucketName(bucketName);
request.setObjectKey(objectName);
TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
return response.getSignedUrl();
}
public static String getSignedUrl(String bucketName, String objectName) {
return getSignedUrl(bucketName, objectName, expire);
}
private static String buildObjectName(String objectName) {
if (StringUtils.isBlank(objectName)) {
return objectName;
}
objectName = objectName.startsWith("/") ? objectName.substring(1) : objectName;
objectName = objectName.contains("?") ? objectName.substring(0, objectName.indexOf("?")) : objectName;
return objectName;
}
public static String getObjectNameByUrl(String url) {
if (StringUtils.isBlank(url)) {
return url;
}
if (url.contains(getBasisUrl())) {
url = url.replace(getBasisUrl(), "");
url = url.contains("?") ? url.substring(0, url.indexOf("?")) : url;
}
return url;
}
}