sean.zhou
2022-11-18 56df98ce4952239fbf7d0e99dbeb0e5c71531d6f
src/main/java/com/dji/sample/component/oss/service/impl/AliyunOssServiceImpl.java
@@ -2,7 +2,11 @@
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
@@ -70,7 +74,10 @@
        }
        OSS ossClient = this.createClient();
        // First check if the object can be fetched.
        ossClient.getObject(bucket, objectKey);
        boolean isExist = ossClient.doesObjectExist(bucket, objectKey);
        if (!isExist) {
            throw new OSSException("The object does not exist.");
        }
        return ossClient.generatePresignedUrl(bucket, objectKey,
                new Date(System.currentTimeMillis() + configuration.getExpire() * 1000));
@@ -79,30 +86,40 @@
    @Override
    public Boolean deleteObject(String bucket, String objectKey) {
        OSS ossClient = this.createClient();
        if (!ossClient.doesObjectExist(bucket, objectKey)) {
            ossClient.shutdown();
            return true;
        }
        ossClient.deleteObject(bucket, objectKey);
        ossClient.shutdown();
        return true;
    }
    @Override
    public byte[] getObject(String bucket, String objectKey) {
    public InputStream getObject(String bucket, String objectKey) {
        OSS ossClient = this.createClient();
        OSSObject object = ossClient.getObject(bucket, objectKey);
        InputStream stream = object.getObjectContent();
        try {
            return stream.readAllBytes();
        try (InputStream input = object.getObjectContent()) {
            return input;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                stream.close();
                ossClient.shutdown();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ossClient.shutdown();
        }
        return new byte[0];
        return InputStream.nullInputStream();
    }
    @Override
    public void putObject(String bucket, String objectKey, InputStream input) {
        OSS ossClient = this.createClient();
        if (ossClient.doesObjectExist(bucket, objectKey)) {
            ossClient.shutdown();
            throw new RuntimeException("The filename already exists.");
        }
        PutObjectResult objectResult = ossClient.putObject(new PutObjectRequest(bucket, objectKey, input, new ObjectMetadata()));
        ossClient.shutdown();
        log.info("Upload File: {}", objectResult.getETag());
    }
    private OSS createClient() {