当前位置: 首页 > article >正文

OSS文件上传

1.在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.在application-dev.yml开发者配置文件中添加

# 阿里云OSS
  alioss:
    endpoint: oss-accelerate.aliyuncs.com # oss全球加速域名
    bucket-name: tangguangyu # 存储空间名称
    access-key-id: LTAI5tSp9arZfkrg6dnyv9Hw # 访问密钥ID
    access-key-secret: 5guoa94EJ8788ld7W5TQSMJYXNYFA1 # 访问密钥Secret

3.创建AliOssProperties 用于读取配置

package com.sky.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "sky.alioss")// 绑定配置文件中的sky.alioss.*
@Data
public class AliOssProperties {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

}

4.将 AliOssProperties 读取并注入到spring容器之中

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  //当容器中没有这个bean对象时,才创建这个对象
    public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){
        log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);
        return new AliOssUtil(
                aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret(),
                aliOssProperties.getBucketName());
    }
}

5.创建阿里云工具类用于上传文件并返回文件名称

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 org.springframework.beans.factory.annotation.Value;

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

6.使用上传

 @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传:{}", file);
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            log.info("原始文件名:{}", originalFilename);
            //截取原文件名称
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            log.info("原文件名称:{}", extension);
            //生成UUID为新文件名称
            String objectName = UUID.randomUUID().toString() + extension;
            //上传到阿里云并返回文件访问路径
            String fullPath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(fullPath);
        } catch (IOException e) {
            log.error("文件上传失败:{}", e);
        }
        return Result.error("上传失败");
    }


http://www.kler.cn/a/397418.html

相关文章:

  • Python 中常用的格式符号
  • vue3:computed
  • Android Osmdroid + 天地图 (二)
  • 如何修改npm包
  • PCA 原理推导
  • 在 Oracle Linux 8.9 上安装Oracle Database 23ai 23.5
  • 基于微信小程序的校园超市购物系统设计与实现,LW+源码+讲解
  • onlyoffice Command service(命令服务)使用示例
  • 【HarmonyOS】鸿蒙应用低功耗蓝牙BLE的使用心得 (三)
  • 要卸载 Grafana 或者从 TiDB 集群中删除 Grafana 服务节点,你需要按以下步骤操作
  • leetcode 35. 搜索插入位置 简单
  • python re模块 详解
  • 在k8s上部署Crunchy Postgres for Kubernetes
  • 流程图图解@RequestBody @RequestPart @RequestParam @ModelAttribute
  • Django的RBAC认证和权限
  • Python + Memcached:分布式应用程序中的高效缓存
  • pytest中的断言:深入解析与实践
  • Net.Core Mvc 添加 log 日志
  • 1、PyTorch介绍与张量的创建
  • 迅睿CMS如何实现文章自动推送百度的便捷方法?
  • 怎样遵守编程规范,减少和控制C++编程中出现的bug?
  • uniapp适配暗黑模式配置plus.nativeUI.setUIStyle适配DarkMode配置
  • phonemizer 获取英文文本句子单词音素 - python实现
  • 智能工厂的设计软件 为了监管控一体化的全能Supervisor 的监督学习 之 序2 架构for认知系统 :机器学习及其行动门上的机器人
  • Gitcode文件历史记录查看和还原
  • 论文解析:基于区块链的去中心化服务选择,用于QoS感知的云制造(四区)