阿里云oss文件上传Java工具类

这是一个Java实现的阿里云OSS文件上传工具类,使用OSSClientBuilder构建OSSClient实例,通过putObject方法上传字节数组形式的文件,并在上传成功后提供文件的访问URL。异常处理包括OSSException和ClientException。
摘要由CSDN通过智能技术生成

阿里云oss文件上传工具类

package com.sky.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public String upload(byte[] bytes, String objectName) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } 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();
            }
        }

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        log.info("文件上传到:{}", stringBuilder.toString());

        return stringBuilder.toString();
    }
}

AliOssProperties.java 配置文件

package com.sky.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里提供一个 Java 版本的阿里云 OSS 工具类,方便上传、下载、删除等操作。 ```java import com.aliyun.oss.ClientConfiguration; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URL; import java.util.Date; import java.util.List; /** * 阿里云 OSS 工具类 */ public class AliyunOSSUtil { private static final Logger LOGGER = LoggerFactory.getLogger(AliyunOSSUtil.class); private static OSS ossClient; /** * 初始化 OSS 客户端 * * @param endpoint OSS 服务的 endpoint * @param accessKeyId 访问 OSS 服务的 accessKeyId * @param accessKeySecret 访问 OSS 服务的 accessKeySecret */ public static void initOSSClient(String endpoint, String accessKeyId, String accessKeySecret) { ClientConfiguration config = new ClientConfiguration(); config.setConnectionTimeout(5000); // 设置连接超时时间,默认50000毫秒 config.setMaxErrorRetry(3); // 设置请求失败后最大重试次数,默认3次 ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, config); } /** * 销毁 OSS 客户端 */ public static void destroyOSSClient() { if (ossClient != null) { ossClient.shutdown(); } } /** * 上传文件到 OSS * * @param bucketName OSS bucket 名称 * @param filePath 本地文件路径 * @param objectName OSS 上的文件名称 * @return 文件 URL */ public static String uploadFile(String bucketName, String filePath, String objectName) { try { // 创建 PutObjectRequest 对象 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath)); // 如果需要上传时设置存储类型与访问权限,请参考以下示例代码。 // ObjectMetadata metadata = new ObjectMetadata(); // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString()); // metadata.setObjectAcl(CannedAccessControlList.Private); // putObjectRequest.setMetadata(metadata); // 上传文件 ossClient.putObject(putObjectRequest); // 获取文件 URL Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000); // 设置 URL 过期时间为 1 小时 URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration); LOGGER.info("Upload file to OSS success, object name: {}, URL: {}", objectName, url); return url.toString(); } catch (Exception e) { LOGGER.error("Upload file to OSS failed, object name: {}", objectName, e); return null; } } /** * 下载 OSS 上的文件 * * @param bucketName OSS bucket 名称 * @param objectName OSS 上的文件名称 * @param localPath 本地存储路径 */ public static void downloadFile(String bucketName, String objectName, String localPath) { try { // 下载文件 OSSObject ossObject = ossClient.getObject(bucketName, objectName); InputStream inputStream = ossObject.getObjectContent(); OutputStream outputStream = new FileOutputStream(localPath); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } outputStream.close(); inputStream.close(); LOGGER.info("Download file from OSS success, object name: {}, local path: {}", objectName, localPath); } catch (Exception e) { LOGGER.error("Download file from OSS failed, object name: {}", objectName, e); } } /** * 判断 OSS 上是否存在指定文件 * * @param bucketName OSS bucket 名称 * @param objectName OSS 上的文件名称 * @return true:存在,false:不存在 */ public static boolean isExist(String bucketName, String objectName) { try { return ossClient.doesObjectExist(bucketName, objectName); } catch (Exception e) { LOGGER.error("Check object exist failed, object name: {}", objectName, e); return false; } } /** * 删除 OSS 上的文件 * * @param bucketName OSS bucket 名称 * @param objectName OSS 上的文件名称 */ public static void deleteFile(String bucketName, String objectName) { try { ossClient.deleteObject(bucketName, objectName); LOGGER.info("Delete file from OSS success, object name: {}", objectName); } catch (Exception e) { LOGGER.error("Delete file from OSS failed, object name: {}", objectName, e); } } /** * 列举 OSS bucket 中的所有文件 * * @param bucketName OSS bucket 名称 * @return 文件列表 */ public static List<OSSObjectSummary> listObjects(String bucketName) { try { ObjectListing objectListing = ossClient.listObjects(bucketName); return objectListing.getObjectSummaries(); } catch (Exception e) { LOGGER.error("List objects failed, bucket name: {}", bucketName, e); return null; } } } ``` 使用方法: ```java // 初始化 OSS 客户端 AliyunOSSUtil.initOSSClient("your endpoint", "your accessKeyId", "your accessKeySecret"); // 上传文件 String fileUrl = AliyunOSSUtil.uploadFile("your bucket name", "your local file path", "your object name"); // 下载文件 AliyunOSSUtil.downloadFile("your bucket name", "your object name", "your local path"); // 判断文件是否存在 boolean isExist = AliyunOSSUtil.isExist("your bucket name", "your object name"); // 删除文件 AliyunOSSUtil.deleteFile("your bucket name", "your object name"); // 列举 bucket 中的所有文件 List<OSSObjectSummary> objectSummaries = AliyunOSSUtil.listObjects("your bucket name"); // 销毁 OSS 客户端 AliyunOSSUtil.destroyOSSClient(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值