目录
官方地址
依赖引入
<!-- huawei OBS -->
<dependency>
<groupId>com.huaweicloud</groupId>
<artifactId>esdk-obs-java</artifactId>
<version>3.20.6.2</version>
</dependency>
yml文件配置
# OBS配置
obs:
ak:
sk:
bucketName:
prefixUrl:
endPoint:
配置类
@Component
@ConfigurationProperties(prefix="huawei.obs")
public class ObsConfig {
/** 密钥ID*/
public static String AK;
/** 密钥*/
public static String SK;
/** 节点*/
public static String END_POINT;
/** 桶名*/
public static String BUCKET_NAME;
/** 图片绑定前缀域名*/
public static String PREFIX_URL;
public void setImagePrefixUrl(String prefixUrl) {
ObsConfig.PREFIX_URL = prefixUrl;
}
public void setAk(String ak) {
ObsConfig.AK = ak;
}
public void setSk(String sk) {
ObsConfig.SK = sk;
}
public void setEndpoint(String endPoint) {
ObsConfig.END_POINT = endPoint;
}
public void setBucketName(String bucketName) {
ObsConfig.BUCKET_NAME = bucketName;
}
}
实现
dubbo接口调用,所以使用了字节传输流,适用于小文件传输
dubbo调用默认不支持MultipartFile 文件类型
@Slf4j
public class ObsUtils {
/**
* 文件上传
* @param file 文件
* @param path 上传路径
* @return 文件全路径
*/
public static String upload(MultipartFile file, String path) {
InputStream in=null;
ObsClient obsClient = null;
try{
//获取流对象
in= new ByteArrayInputStream(file.getBytes());
// 创建ObsClient实例
obsClient = new ObsClient(ObsConfig.AK, ObsConfig.SK, ObsConfig.END_POINT);
// 使用访问OBS
obsClient.putObject(ObsConfig.BUCKET_NAME, path, in);
log.info("--->文件上传路径为:{}",path);
} catch (IOException e) {
log.info("输出流关闭失败!",e);
} finally {
try{
if(in!=null)
{
in.close();
}
}catch (IOException e){
log.info("输出流关闭失败!",e);
}
try{
if(obsClient!=null){
// 关闭obsClient
obsClient.close();
}
}catch (IOException e){
log.info("输出流关闭失败!",e);
}
}
return ObsConfig.PREFIX_URL + "/" + path;
}
/**
* 单个文件下载
* @param obsUtilsVo
* @return
*/
@Override
public Response<ObsUtilsVO> downloadSingleFile(ObsUtilsVO obsUtilsVo) {
//文件路径 文件 校验
if(obsUtilsVo.getPath().isEmpty()){
return ResponseWrapper.fail("文件路径为空!");
}
/**
* 获取输出流
*/
InputStream input = null;
ObsClient obsClient = null;
ByteArrayOutputStream output = null;
try{
// 创建ObsClient实例
obsClient = new ObsClient(ObsProperties.AK, ObsProperties.SK, ObsProperties.END_POINT);
// 使用访问OBS
ObsObject obsObject = obsClient.getObject(ObsProperties.BUCKET_NAME, obsUtilsVo.getPath());
log.info("Object content:{}",obsObject);
input = obsObject.getObjectContent();
output = new ByteArrayOutputStream();
IoUtils.copy(input, output);
byte[] buffer = output.toByteArray();
obsUtilsVo.setFileBytes(buffer);
} catch (IOException e) {
e.printStackTrace();
}
finally {
try{
assert input != null;
input.close();
assert output != null;
output.close();
obsClient.close();
}catch (IOException e){
e.printStackTrace();
System.err.println("流对象关闭失败!");
}
}
//返回文件流
return ResponseWrapper.success(obsUtilsVo);
}
}