栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot整合阿里云OSS进行文件上传

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot整合阿里云OSS进行文件上传

本篇文章我们来介绍如何用Springboot整合阿里云OSS进行文件上传。

 

1、开通阿里云OSS

第一步:点击立即开通

https://www.aliyun.com/product/oss

第二步:进入管理控制台

第三步:查看API帮助文档

https://help.aliyun.com/document_detail/31947.html?spm=5176.8465980.help.dexternal.41231450z6Cv3R

2、创建 bucket

存储类型:低频访问存储

读写权限:公共读

3、创建子账户

https://ram.console.aliyun.com/users

第一步:点击创建用户

第二步:填写相关信息,然后点击确定

开通完成之后,就会有个 AccessKey ID 和 AccessKey Secret。

PS:创建账户后,开通了 Open API 调用访问,要及时保存 AccessKey,否则关闭后无法再次获取。

4、给子账户分配OSS管理权限

添加OSS权限

5、整合SDK-OSS

https://github.com/alibaba/aliyun-spring-boot/blob/master/aliyun-spring-boot-samples/aliyun-oss-spring-boot-sample/README-zh.md

5.1 引入依赖 liyun-oss-spring-boot-starter

在 gulimall-common 模块中引入:

PS:这里和官方引入的依赖不一样。


    com.alibaba.cloud
    spring-cloud-starter-alicloud-oss
    2.2.0.RELEASE

5.2 在配置文件中配置 OSS 服务对应的 accessKey、secretKey 和 endpoint。

spring:
  cloud:
    alicloud:
      oss:
        endpoint: 
      access-key: 
      secret-key: 

5.3 测试

package com.atguigu.gulimall.product;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

@SpringBootTest
class GulimallProductApplicationTests {

    @Autowired
    OSSClient ossClient;

    @Test
    public void testUpload() throws FileNotFoundException {
        //上传文件流。
        InputStream inputStream = new FileInputStream("/Users/yushuai/Downloads/idea.jpeg");
        ossClient.putObject("itcoke", "test.jpeg", inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();
        System.out.println("上传成功.");
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1035479.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号