阿里云OSS存储,文件上传与文件删除
maven依赖:
<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.10.2</version></dependency>
代码:
package com.mk.oss.utils;import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import lombok.Getter;
import lombok.Setter;@Service
@Slf4j
public class OssClient {private OSS create(BucketAccount bucketAccount) {String accessKeyId = bucketAccount.getAccessKeyId();String accessKeySecret = bucketAccount.getAccessKeySecret();OSS ossClient = new OSSClientBuilder().build(bucketAccount.getEndpoint(), accessKeyId, accessKeySecret);return ossClient;}public UploadResult upload(InputStream data, BucketAccount bucketAccount, String fileName) throws Throwable {String bucket = bucketAccount.getBucket();OSS ossClient = null;try {ossClient = create(bucketAccount);PutObjectResult putObjectResult = ossClient.putObject(bucket, fileName, data);String durl = getUrl(ossClient, bucketAccount, fileName);UploadResult result = new UploadResult();result.setBucketName(bucket);result.setFileName(fileName);result.setETag(putObjectResult.getETag());result.setDownloadUrl(durl);return result;} catch (Throwable e) {log.warn("上传OSS异常,bucket:" + bucket + ", fileName:" + fileName, e);throw e;} finally {if (ossClient != null) {ossClient.shutdown();}}}private String getUrl(OSS ossClient, BucketAccount bucketAccount, String fileName) throws Exception {Calendar cal = Calendar.getInstance();cal.setTime(new Date());cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 100);Date date = cal.getTime();URL url = ossClient.generatePresignedUrl(bucketAccount.getBucket(), fileName, date);String durl = url.toString();return durl;}public DeleteResult delete(BucketAccount bucketAccount, String fileName) throws Throwable {String bucket = bucketAccount.getBucket();OSS ossClient = null;try {ossClient = create(bucketAccount);ossClient.deleteObject(bucket, fileName);return new DeleteResult(bucket);} catch (Throwable e) {log.warn("删除OSS异常,bucket:" + bucket + ", fileName:" + fileName, e);throw e;} finally {if (ossClient != null) {ossClient.shutdown();}}}@Setter@Getterpublic static class BucketAccount{private String bucket;private String accessKeyId;private String accessKeySecret;private String endpoint;}@Setter@Getterpublic static class UploadResult {private String eTag;private String downloadUrl;private String bucketName;private String fileName;}@Setter@Getterpublic static class DeleteResult {private String bucketName;public DeleteResult(String bucketName) {this.bucketName = bucketName;}}
}