阿里云OSS配置及其使用

本文介绍了如何在Java项目中通过Maven引入阿里云OSSSDK,并展示了如何配置工具类进行文件上传,包括访问凭证的获取和上传操作的实现。同时给出了一个简单的Controller示例用于处理文件上传请求。

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

一、导入maven依赖

<dependency>
   <groupId>com.aliyun.oss</groupId>
   <artifactId>aliyun-sdk-oss</artifactId>
   <version>3.10.2</version>
</dependency>
<!-- 顺便导入一下lombok -->
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
</dependency>

二、导入工具类

这里需要配置一下自己的 endpoint、accessKeyId、accessKeySecret、bucketName,需要去自己的阿里云查看

阿里云登录 - 欢迎登录阿里云,安全稳定的云计算服务平台

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
@Slf4j
public class AliOssUtil {

    /*
    *	去aliyun oss管理控制台查看
    */
    private static String endpoint="自己的endpoint";
    private static String accessKeyId="密钥ID";
    private static String accessKeySecret="密钥密码";
    private static String bucketName="bucket名字";

    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public static 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();
    }
}

到这里已经可以使用 AliOssUtil这个工具了,下面是我写的一个文件上传的方法

三、文件上传的Controller

  想自定义Controller的小伙伴这一步可以自己写!

import com.example.testutils.utils.AliOssUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileUpLoadController {

    @PostMapping("/upload")
    public String upload(MultipartFile file){
        try {
            String originName= file.getOriginalFilename();
            String newName=UUID.randomUUID()+originName.substring(originName.lastIndexOf("."));
            AliOssUtil.upload(file.getBytes(), newName);
        } catch (IOException e) {
            return "上传失败!";
        }
        return "上传成功!";
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值