• 文件上传OSS实现


    1). 定义OSS相关配置

    在sky-server模块

    application-dev.yml

    sky:
      alioss:
        endpoint: oss-cn-hangzhou.aliyuncs.com
        access-key-id: LTAI5tPeFLzsPPT8gG3LPW64
        access-key-secret: U6k1brOZ8gaOIXv3nXbulGTUzy6Pd7
        bucket-name: sky-take-out
    

    application.yml

    spring:
      profiles:
        active: dev    #设置环境
    sky:
      alioss:
        endpoint: ${sky.alioss.endpoint}
        access-key-id: ${sky.alioss.access-key-id}
        access-key-secret: ${sky.alioss.access-key-secret}
        bucket-name: ${sky.alioss.bucket-name}
    
    

    2). 读取OSS配置

    在sky-common模块中,已定义

    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;
    
    }
    

    3). 生成OSS工具类对象

    在sky-server模块

    package com.sky.config;
    
    import com.sky.properties.AliOssProperties;
    import com.sky.utils.AliOssUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * 配置类,用于创建AliOssUtil对象
     */
    @Configuration
    @Slf4j
    public class OssConfiguration {
    
        @Bean
        @ConditionalOnMissingBean
        public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){
            log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);
            return new AliOssUtil(aliOssProperties.getEndpoint(),
                    aliOssProperties.getAccessKeyId(),
                    aliOssProperties.getAccessKeySecret(),
                    aliOssProperties.getBucketName());
        }
    }
    

    其中,AliOssUtil.java已在sky-common模块中定义

    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();
        }
    }
    

    4). 定义文件上传接口

    在sky-server模块中定义接口

    package com.sky.controller.admin;
    
    import com.sky.constant.MessageConstant;
    import com.sky.result.Result;
    import com.sky.utils.AliOssUtil;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import lombok.extern.slf4j.Slf4j;
    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.RestController;
    import org.springframework.web.multipart.MultipartFile;
    import java.io.IOException;
    import java.util.UUID;
    
    /**
     * 通用接口
     */
    @RestController
    @RequestMapping("/admin/common")
    @Api(tags = "通用接口")
    @Slf4j
    public class CommonController {
    
        @Autowired
        private AliOssUtil aliOssUtil;
    
        /**
         * 文件上传
         * @param file
         * @return
         */
        @PostMapping("/upload")
        @ApiOperation("文件上传")
        public Result<String> upload(MultipartFile file){
            log.info("文件上传:{}",file);
    
            try {
                //原始文件名
                String originalFilename = file.getOriginalFilename();
                //截取原始文件名的后缀   dfdfdf.png
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                //构造新文件名称
                String objectName = UUID.randomUUID().toString() + extension;
    
                //文件的请求路径
                String filePath = aliOssUtil.upload(file.getBytes(), objectName);
                return Result.success(filePath);
            } catch (IOException e) {
                log.error("文件上传失败:{}", e);
            }
    
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
    

    提示:
    @ConditionalOnMissingBean是用于修饰Bean的一个注解,在项目启动时开始自动化配置注册生成Bean,当某个类型的Bean被注册之后,如果再注册相同类型的Bean就会失败,该注解会保证Spring容器中只有一个Bean类型的实例,当注册多个相同类型的Bean时,会出现异常。当一个接口有多个实现类时,如果只希望它有一个实现类,那就在其他的各个实现类上加上这个注解。
    @ConditionalOnMissingBean作用在@Bean定义上,也就是说在容器加载它作用的Bean时,检查容器中是否存在目标类型(@ConditionalOnMissingBean注解的value值)的Bean了,如果存在则跳过Bean的默认加载动作,如果不存在则加载该Bean完成注册。
    参考:参考文章

  • 相关阅读:
    香港科技大学广州|智能制造学域&机器人与自主系统学域博士招生宣讲会—中国科学技术大学专场
    [Interview]Java 面试宝典系列之 Java 集合类
    2022-8-31 第六小组 瞒春 学习笔记
    Spring Ioc源码分析系列--自动注入循环依赖的处理
    当后端给我返回了302状态码
    C++基础算法教程|图论入门(一)
    网页制作基础大三dw作业 基于HTML+CSS+JavaScript新能源汽车租赁(6个页面)
    码蹄集 - MT3111· 赋值
    L4.linux命令每日一练 -- 第二章 文件和目录操作命令 -- pwd和cd命令
    mysql基本操作命令
  • 原文地址:https://blog.csdn.net/BlackBaby_aha/article/details/138924541