接上文aliyun-oss-01
<dependency>
<groupId>com.aliyun.ossgroupId>
<artifactId>aliyun-sdk-ossartifactId>
<version>3.11.3version>
dependency>
<dependency>
<groupId>javax.xml.bindgroupId>
<artifactId>jaxb-apiartifactId>
<version>2.3.1version>
dependency>
<dependency>
<groupId>javax.activationgroupId>
<artifactId>activationartifactId>
<version>1.1.1version>
dependency>
<dependency>
<groupId>org.glassfish.jaxbgroupId>
<artifactId>jaxb-runtimeartifactId>
<version>2.3.3version>
dependency>
OSSClient是OSS的Java客户端,用于管理存储空间和文件等OSS资源。使用Java SDK发起OSS请求,您需要初始化一个OSSClient实例,并根据需要修改ClientConfiguration的默认配置项。
@Value("${oss.endpoint}")
private String endpoint;
@Value("${oss.AccessKeyID}")
private String accessKeyID;
@Value("${oss.AccessKeySecret}")
private String accessKeySecret;
@Value("$oss.bucketName")
private String bucketName;
这的Oss 用完之后 是需要关闭的,如果不关闭,会造成内存泄露
/**
* 使用OSS域名新建OSSClient(其中之一)
*
* @return OssClient
*/
public OSS ossClientCreate() {
final OSS build = new OSSClientBuilder().build(endpoint, accessKeyID, accessKeySecret);
log.info("OSSClient 新建成功");
return build;
}
创建bucket时,bucket的名字一定要是没有被别人和自己取过的
他人存在的bucketName,则会出现以下信息
[ErrorCode]: AccessDenied
[RequestId]: xxxxxxx
[HostId]: image.oss-cn-shanghai.aliyuncs.com
[ResponseError]:
<Error>
<Code>AccessDeniedCode>
<Message>The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.Message>
<RequestId>xxxxxxxxxRequestId>
<HostId>image.oss-cn-shanghai.aliyuncs.comHostId>
<Bucket>imageBucket>
<Endpoint>oss-cn-hangzhou.aliyuncs.comEndpoint>
Error>
自己存在的bucketNam
[ErrorCode]: BucketAlreadyExists
[RequestId]: xxxxxxxxx
[HostId]: data-lujy.oss-cn-shanghai.aliyuncs.com
[ResponseError]:
<Error>
<Code>BucketAlreadyExistsCode>
<Message>The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.Message>
<RequestId>xxxxxxxxxxxRequestId>
<HostId>data-lujy.oss-cn-shanghai.aliyuncs.comHostId>
<BucketName>data-lujyBucketName>
Error>
tip:这两者的区别在于,第一个相当于去访问一个bucket但是密码和账户错了,从而导致了拒绝访问。第二个则是账户和密码正确,成功访问了,当时在创建的时候,出现了相同bucket。
/**
* 创建一个bucket
*
* @param oss OSSClient
* @param bucketName 桶的名称
*/
public Bucket createBucket(OSS oss, String bucketName) {
final boolean b = oss.doesBucketExist(bucketName);
if (b) {
log.warn("该名称已存在:{}", bucketName);
return null;
} else {
return oss.createBucket(bucketName);
}
}
oss的上传文件方式很多,这里只是采用了比较简单的一种
/**
* 简单上传文件
* @param oss OssClient
* @param objectName 保存为指定的路径名称 需全路径如 image/day01/xxx.txt
* @param inputStream 文件流
* @return
*/
public Boolean uploadFile(OSS oss, String objectName, InputStream inputStream) {
try {
final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
//上传文件
final PutObjectResult putObjectResult = oss.putObject(putObjectRequest);
return putObjectResult != null;
} catch (OSSException | ClientException e) {
e.printStackTrace();
return false;
}
}
流下载
/**
* 流下载
*
* @param oss
* @param objectName
* @return
*/
public void downloadFileStream(OSS oss, String objectName) {
final OSSObject object = oss.getObject(bucketName, objectName);
final String key = object.getKey();
System.out.println(key);
try (
InputStream is = object.getObjectContent();
OutputStream os = new FileOutputStream(new File("src/main/resources/static/" + objectName));
) {
//创建缓存区
byte[] bytes = new byte[2048];
int length;
while ((length = is.read(bytes)) != -1) {
os.write(bytes, 0, length);
}
log.info("全部写入缓存区");
os.flush();
} catch (Exception e) {
e.printStackTrace();
log.error("流读取出现错误:{}", e.getMessage());
}
}
本地下载
/**
* 下载到本地
*
* @param oss OssClient
* @param objectName oss 中的文件地址
* @param localFile 本地文件地址 如果存在 则会直接覆盖不会新建
*/
public Boolean downloadFileLocal(OSS oss, String objectName, File localFile) {
final ObjectMetadata omd;
try {
final GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);
omd = oss.getObject(getObjectRequest, localFile);
if (omd == null) {
log.info("本地文件下载失败,原因:ObjectMetadata 为空");
return false;
} else {
log.info("下载成功");
return true;
}
} catch (OSSException | ClientException e) {
e.printStackTrace();
log.info("下载出现异常:{}", e.getMessage());
return false;
}
}
// TODO: 2021/2/9 范围下载(未完成) // TODO: 2021/2/9 断电续传下载(未完成) // TODO: 2021/2/9 限定条件下载(未完成)