SpringBoot2.x+阿里云oss开通权限配置+ 文件上传代码

 

对象存储OSS(Object Storage Service)是阿里云提供的海量、安全、低成本、高持久的云存储服务。其数据设计持久性不低于99.9999999999%(12个9),服务设计可用性不低于99.995%。

步骤:开通OSS,建用户,给权限,创建个桶,验证下上传功能,然后就是重点编码环节,再最后测试验证-->完成~

一、开通阿里云OSS
    有阿里云账号、实名认证

    官方学习路径:https://help.aliyun.com/learn/learningpath/oss.html
    OSS介绍:https://www.aliyun.com/product/oss

     企业使用可根据需要购买,如果是学习使用的话,可以忽略。因为上传那几个图片、文件验证功能,貌似不收费。


 OSS控制台:https://oss.console.aliyun.com/bucket 

初次进入oss控制台,点击立即开通。

  

 二、开通后的操作
    创建Bucket


    上传文件

新建目录

上传完成

   访问文件

 三、权限相关知识点

知识延伸之当下管理系统所用的一些权限

ACL: Access Control List 访问控制列表
    以前盛行的一种权限设计,它的核心在于用户直接和权限挂钩
    优点:简单易用,开发便捷
    缺点:用户和权限直接挂钩,导致在授予时的复杂性,比较分散,不便于管理
    例子:linux系统 常见的文件系统权限设计, 直接给用户加权限

RBAC: Role Based Access Control
    基于角色的访问控制系统。权限与角色相关联,用户通过成为适当角色的成员而得到这些角色的权限
    优点:简化了用户与权限的管理,通过对用户进行分类,使得角色与权限关联起来
    缺点:开发对比ACL相对复杂
    例子:基于RBAC模型的权限验证框架与应用 Apache Shiro、spring Security

阿里云的权限管理介绍:

        阿里云用于各个产品的权限,基于RBAC、ACL模型都有,进行简单管理账号、统一分配权限、集中管控资源,从而建立安全、完善的资源控制体系。
众多产品,一般采用子账号进行分配权限,防止越权攻击

阿里云访问控制:https://ram.console.aliyun.com/overview

第一步创建用户

创建好后保存信息 

给用户添加权限

 权限添加中

 四:编码环节

添加阿里云OSS的SDK
    地址:https://help.aliyun.com/document_detail/32008.html

pom.xml

    <!--阿里云oss-->
            <dependency>
                <groupId>com.aliyun.oss</groupId>
                <artifactId>aliyun-sdk-oss</artifactId>
                <version>3.10.2</version>
            </dependency>

application.yml

aliyun:
  oss:
    endpoint: oss-cn-xxxx.aliyuncs.com
    access-key-id: LTAIxxxxxxxxxxduTeWyHajv
    access-key-secret: KPdQxxxxxxxxxyi5PBMEWaA4hyoel
    bucketname: cloud-link

  endpoit来自:外网访问的地域节点

 配置类

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;


@ConfigurationProperties(prefix = "aliyun.oss")
@Configuration
@Data
public class OSSConfig {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketname;
}

开发controller 

一般文件的上传流程:
    先上传文件,返回url地址,再和普通表单一并提交(推荐这种,更加灵活,失败率低)
    文件和普通表单一并提交(设计流程比较多,容易超时和失败)
    注意:默认SpringBoot最大文件上传是1M,大家测试的时候记得关注下

  @RequestPart注解 接收文件以及其他更为复杂的数据类型

import net.wnn.enums.BizCodeEnum;
import net.wnn.service.FileService;
import net.wnn.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/v1/account")
public class AccountController {
    @Autowired
    private FileService fileService;
    /**
     * 文件上传 最大默认1M
     *  文件格式、拓展名等判断
     * @param file
     * @return
     */
    @PostMapping("upload")
    public JsonData uploadUserImg(@RequestPart("file")MultipartFile file){

        String result = fileService.uploadUserImg(file);

        return result !=null ? JsonData.buildSuccess(result):JsonData.buildResult(BizCodeEnum.FILE_UPLOAD_USER_IMG_FAIL);

    }


}

service 和seviceimpl

import org.springframework.web.multipart.MultipartFile;


public interface FileService {

    /**
     * 文件上传
     * @param file
     * @return
     */
    String uploadUserImg(MultipartFile file);
}

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import net.wnn.config.OSSConfig;
import net.wnn.service.FileService;
import net.wnn.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String uploadUserImg(MultipartFile file) {
        String bucketName = ossConfig.getBucketname();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        //oss客户端构建
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

        //获取文件原始名称 xxx.jpg
        String originalFilename = file.getOriginalFilename();

        //jdk8语法日期格式
        LocalDateTime ldt = LocalDateTime.now();
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        //user/2022/12/12/sdsdwe/
        String folder = pattern.format(ldt);
        String fileName = CommonUtil.generateUUID();
        String extendsion = originalFilename.substring(originalFilename.lastIndexOf("."));

        //在oss上的bucket创建文件夹
        String newFilename = "user/"+folder+"/"+fileName+extendsion;

        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, newFilename, file.getInputStream());
            //拼装返回路径
            if(putObjectResult!=null){
                String imgUrl = "https://"+bucketName+"."+endpoint+"/"+newFilename;
                return imgUrl;
            }

        } catch (IOException e) {
            log.error("文件上传失败:{}",e.getMessage());
        }finally {
            ossClient.shutdown();
        }

        return null;
    }
}

使用postman调用成功:

顺利存储到阿里云中。通过返回的url可以浏览器直接访问下载

 ~~~~完成啦~~~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值