java对接天翼云OOS实现文件存储
1. 注册天翼云账户、开通对象存储、创建容器
2. 获取AccessKeyID、SecretAccessKey
确定四个参数,在application.yml中填入以下配置
# 文件上传 OOS (天翼云)
oos:
config:
access-key: 填入之前获取的AccessKeyID
secret-key: 填入对应密钥SecretAccessKey
endpoint: oos-hazz.ctyunapi.cn(可以直接填此端点,不需要动)
bucket: 容器名称
3. maven中央仓库中没有该jar包,官网下载java-oos-sdk-6.5.3.jar到本地,或者上传到maven私服下
下载链接 java-oos-sdk
4. 下载后放入项目lib目录下,在pom.xml文件中添加相关依赖
<!--天翼云OOS-->
<dependency>
<groupId>cn.ctyun</groupId>
<artifactId>ctyun-sdk-oss</artifactId>
<version>6.5.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/oos-java-sdk-6.5.3.jar</systemPath>
</dependency>
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<dependency>
<groupId>org.sejda.imageio</groupId>
<artifactId>webp-imageio</artifactId>
<version>0.1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
5. 添加配置类
@Data
@Component
public class OosClientConfig {
@Value("${oos.config.access-key}")
private String accessKey;
@Value("${oos.config.secret-key}")
private String secretKey;
@Value("${oos.config.endpoint}")
private String endpoint;
@Value("${oos.config.bucket}")
private String bucket;
@Bean
public AmazonS3 oosClient() {
ClientConfiguration clientConfig = new ClientConfiguration();
// 设置连接的超时时间,单位毫秒
clientConfig.setConnectionTimeout(30 * 1000);
// 设置 socket 超时时间,单位毫秒
clientConfig.setSocketTimeout(30 * 1000);
clientConfig.setProtocol(Protocol.HTTP); //设置 http
// 设置 V4 签名算法中负载是否参与签名,关于签名部分请参看《OOS 开发者文档》
S3ClientOptions options = new S3ClientOptions();
options.setPayloadSigningEnabled(true);
// 创建 client
AmazonS3 oosClient = new AmazonS3Client(
new PropertiesCredentials(accessKey, secretKey), clientConfig);
// 设置 endpoint
oosClient.setEndpoint(endpoint);
//设置选项
oosClient.setS3ClientOptions(options);
return oosClient;
}
}
6. 实现工具类,这里直接写成Service服务类,方法一样,可进行适当修改
@Log4j2
@Service
public class OosService {
@Autowired
private OosClientConfig oosClientConfig;
/**
* @Desecription: 上传文件
*/
public String uploadFile(MultipartFile file, String fileName) {
InputStream inputStream = null;
String pathUrl = "";
try {
inputStream = file.getInputStream();
AmazonS3 ossClient = oosClientConfig.oosClient();
String remoteFilePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String dir = remoteFilePath + "/"; // 用户上传文件时指定的前缀。
// 创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
String suffix = fileName.substring(fileName.lastIndexOf("."));
String path = dir + IdWorker.getIdStr() + suffix;
try {
objectMetadata.setContentLength(inputStream.available());
// 上传文件
log.info("开始上传文件到oss");
log.info("bucket: " + oosClientConfig.getBucket());
log.info("path: " + path);
log.info("inputStream: " + inputStream);
log.info("objectMetadata: " + objectMetadata);
ossClient.putObject(oosClientConfig.getBucket(), path, inputStream, objectMetadata);
// URL url = ossClient.generatePresignedUrl(new GeneratePresignedUrlRequest(oosClientConfig.getBucket(), path));
String url = generatePresignedUrl(path);
pathUrl = url;
} catch (Exception e) {
log.error("上传文件到oos失败", e);
} finally {
if (ossClient != null) {
((AmazonS3Client) ossClient).shutdown();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return pathUrl;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
/**
* @Desecription: 删除文件
*/
public boolean deleteFile(String filePath, String fileName) {
AmazonS3 ossClient = oosClientConfig.oosClient();
String path = filePath + fileName;
boolean exist = ossClient.doesBucketExist(oosClientConfig.getEndpoint());
if (!exist) {
log.error("从OSS存储删除的文件不存在,path={}", path);
return false;
} else {
try {
ossClient.deleteObject(oosClientConfig.getEndpoint(), path);
} catch (Exception e) {
log.error("从天翼云OSS删除文件出错,path={}", path, e);
return false;
} finally {
if (ossClient != null) {
try {
((AmazonS3Client) ossClient).shutdown();
} catch (AmazonClientException e) {
e.printStackTrace();
}
}
}
return true;
}
}
/**
* @Desecription: 获取文件下载地址 ,并设置过期时间
*/
public String generatePresignedUrl(String fileKey) throws ParseException {
GeneratePresignedUrlRequest request = new
GeneratePresignedUrlRequest(oosClientConfig.getBucket(), fileKey);
/* SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date expireDate = sdf.parse("2031-01-01");
request.setExpiration(expireDate);*/
URL url = oosClientConfig.oosClient().generatePresignedUrl(request);
return url.toString();
}
}