阿里云OSS 上传、移除工具类

本文介绍了如何在Java项目中引入阿里云OSSSDK,配置相关依赖,以及如何编写工具类实现文件上传、下载和删除操作,包括单个文件和批量对象的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 引入依赖
<dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.15.1</version>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- no more than 2.3.3-->
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>2.3.3</version>
        </dependency>
  1. 填写配置文件 .yml
aliyun:
  oss:
    accessKeyId: *****************
    accessKeySecret: *****************
    endpoint: *****************
    bucketName: *****************
  1. 编写工具类
/**
 * 上传文件到阿里云
 * 基本路径: eg:https://yi-ban-jia.oss-cn-beijing.aliyuncs.com/wuyu.png
 */
@ConfigurationProperties(prefix = "aliyun.oss")
@Component
public class AliYunOSSUtil {

    private static String endpoint;
    private static String bucketName;
    private static String accessKeyId;
    private static String accessKeySecret;
	
    public static String putObject(InputStream inputStream, String suffix) {
        String objectName = UUID.fastUUID() + "." + suffix;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, objectName, inputStream);
        return getBaseUrl() + objectName;
    }

    public static String putObject(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = StringUtils.getFilenameExtension(originalFilename);
        String objectName = UUID.fastUUID() + "." + suffix;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName, objectName, file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return getBaseUrl() + objectName;
    }

    /**
     * 通过 对象名 删除 对象
     *
     * @param objectName 要删除的文件完整路径。文件完整路径中不能包含Bucket名称
     */
    public static void removeObject(String objectName) {
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 通过 对象名列表批量移除
     *
     * @param objectNameList
     */
    public static void removeBatchObjects(List<String> objectNameList) {
        OSS ossClient = null;
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(objectNameList).withEncodingType("url"));
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
        try {
            for (String obj : deletedObjects) {
                String deleteObj = URLDecoder.decode(obj, "UTF-8");
                System.out.println(deleteObj);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static String getBaseUrl() {
        return "https://" + bucketName + "." + endpoint.substring(8) + "/";
    }

    public void setEndpoint(String endpoint) {
        AliYunOSSUtil.endpoint = endpoint;
    }

    public void setBucketName(String bucketName) {
        AliYunOSSUtil.bucketName = bucketName;
    }

    public void setAccessKeyId(String accessKeyId) {
        AliYunOSSUtil.accessKeyId = accessKeyId;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        AliYunOSSUtil.accessKeySecret = accessKeySecret;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值