如何简单方便的在springboot项目中使用OSS服务(通用方法)

我的笔记会更新至我的hexo博客,欢迎访问
BDsnake’s Blog

前言

我的博客: bdsnake.top
本篇文章介绍如何在springboot项目中配置OSS服务,用一个Service类简单实现上传文件与删除文件的操作

步骤

步骤1:创建存储桶

在阿里云OSS创建存储桶

image-20220728172049658

步骤2:创建RAM授权策略

image-20220728172429705

image-20220728172450828

记录AccessKeyId与accessKeySecret,后面会用

步骤3:在项目中添加依赖

            <!-- 阿里云oss存储api -->
            <dependency>
                <groupId>com.aliyun.oss</groupId>
                <artifactId>aliyun-sdk-oss</artifactId>
                <version>${oss.version}</version>
            </dependency>

步骤4:编写接口与实现类

写两个方法

public interface OssService {
    String upload(MultipartFile file, String path);
    boolean delete(String relativePath);
}
@Service
public class OssServiceImpl implements OssService {
    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    String endpoint = "xxx";
    // 阿里云账号AccessKey
    String accessKeyId = "xxx";
    String accessKeySecret = "xxx";
    String bucketName="xxx";
    @Override
    public String upload(MultipartFile file, String path) {
//        ossClint构建
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
//            文件转化为字节流上传
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,path,new ByteArrayInputStream(file.getBytes()));
            oss.putObject(putObjectRequest);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            oss.shutdown();
        }
        return "your link"+path;
    }
    public boolean delete(String relativePath){
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            oss.deleteObject(bucketName,relativePath);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }finally {
            oss.shutdown();
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值