云存储解决方案-阿里云OSS

云存储解决方案-阿里云OSS

1. 阿里云OSS简介

​ 阿里云对象存储服务(Object Storage Service,简称OSS)为您提供基于网络的数据存取服务。使用OSS,您可以通过网络随时存储和调用包括文本、图片、音频和视频等在内的各种非结构化数据文件。
阿里云OSS将数据文件以对象(object)的形式上传到存储空间(bucket)中。

​ 您可以进行以下操作:

  • 创建一个或者多个存储空间,向每个存储空间中添加一个或多个文件。
  • 通过获取已上传文件的地址进行文件的分享和下载。
  • 通过修改存储空间或文件的属性或元信息来设置相应的访问权限。
  • 在阿里云管理控制台执行基本和高级OSS任务。
  • 使用阿里云开发工具包或直接在应用程序中进行RESTful API调用执行基本和高级OSS任务

2. OSS开通

(1)打开https://www.aliyun.com/ ,申请阿里云账号并完成实名认证。

在这里插入图片描述

(2)充值 (可以不用做)

(3)开通OSS

登录阿里云官网。 点击右上角的控制台。

在这里插入图片描述

将鼠标移至产品,找到并单击对象存储OSS,打开OSS产品详情页面。在OSS产品详情页中的单击立即开通。

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

开通服务后,在OSS产品详情页面单击管理控制台直接进入OSS管理控制台界面。您也可以单击位于官网首页右上方菜单栏的控制台,进入阿里云管理控制台首页,然后单击左侧的对象存储OSS菜单进入OSS管理控制台界面

在这里插入图片描述

(4)创建存储空间

新建Bucket,命名为 hmleadnews ,读写权限为 公共读

在这里插入图片描述

3. OSS快速入门

参考文档官方

(1)创建测试工程,引入依赖

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.15.1</version>
</dependency>

(2)新建类和main方法

import org.junit.jupiter.api.Test;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import java.io.FileInputStream;
import java.io.InputStream;

public class AliOssTest {

    @Test
    public void testOss(){
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "---------------------";
        String accessKeySecret = "-----------------------";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "-----------";
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        String objectName = "0001.jpg";
        // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
        String filePath= "C:\\Users\\Administrator\\Pictures\\Saved Pictures\\10.jpg";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = new FileInputStream(filePath);
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
        } 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 (Exception 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();
            }
        }
    }
}

4. 获取AccessKeyId

在这里插入图片描述

5. 实现文件上传到OSS存储

1)将配置信息相关存储到配置文件中吗,access-key-id和 access-key-secre填写自己对应的

aliyun:
  oss:
    endpoint: oss-cn-beijing.aliyuncs.com
    access-key-id: LTAI5t88g*******
    access-key-secret: lWcMlcChSGetL******
    bucket-name: big-event-springboot-vue-3

2)编写从配置文件中获取相关信息的实体类AliOSSProperties

package com.shisan.utils;

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

/**
 * @Author:shisan
 * @Date:2024/4/21 9:18
 */
@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliOSSProperties {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
}

3)工具类AliOSSUtils

package com.shisan.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/** 阿里云 OSS 工具类 */
@Component
public class AliOSSUtils {

  /*@Value("${aliyun.oss.endpoint}")
  private String endpoint;
  @Value("${aliyun.oss.accessKeyId}")
  private String accessKeyId;
  @Value("${aliyun.oss.accessKeySecret}")
  private String accessKeySecret;
  @Value("${aliyun.oss.bucketName}")
  private String bucketName;*/
  @Autowired private AliOSSProperties aliOSSProperties;

  /** 实现上传图片到OSS */
  public String upload(MultipartFile file) throws IOException {
    String endpoint = aliOSSProperties.getEndpoint();
    String accessKeyId = aliOSSProperties.getAccessKeyId();
    String accessKeySecret = aliOSSProperties.getAccessKeySecret();
    String bucketName = aliOSSProperties.getBucketName();
    // 获取上传的文件的输入流
    InputStream inputStream = file.getInputStream();

    // 避免文件覆盖
    String originalFilename = file.getOriginalFilename();
    String fileName =
        UUID.randomUUID().toString()
            + originalFilename.substring(originalFilename.lastIndexOf("."));

    // 上传文件到 OSS
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    ossClient.putObject(bucketName, fileName, inputStream);

    // 文件访问路径
      String url = "https://"+bucketName+"."+endpoint.substring(endpoint.indexOf("/")+1)+"/"+fileName;
    // 关闭ossClient
    ossClient.shutdown();
    return url; // 把上传到oss的路径返回
  }
}

4) 根据开发接口编写FileUploadController

package com.shisan.controller;

import com.shisan.pojo.Result;
import com.shisan.utils.AliOSSUtils;
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.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author:shisan @Date:2024/5/17 22:30
 */
@RestController
@Slf4j
public class FileUploadController {

  @Autowired private AliOSSUtils aliOSSUtils;

  /*// 本地存储文件
  @PostMapping("/upload")
  public Result upload(String username, Integer age, MultipartFile image) throws Exception {
      log.info("文件上传:{},{},{}", username, age, image);
      // 获取原始文件名
      String filename = image.getOriginalFilename();


      // 构造长度固定的UUID(唯一标识)
      int index = filename.lastIndexOf(".");
      String extname = filename.substring(index);
      String newFileName = UUID.randomUUID().toString() + extname;
      log.info("新的文件名{}", newFileName);

      // 永久的上传到本地文件
      image.transferTo(new File("D:\\upload\\img\\" + newFileName));
      return Result.success();
  }*/

  @PostMapping("/upload")
  public Result upload(MultipartFile image) throws IOException {
    log.info("文件上传{}", image.getOriginalFilename());
    // 上传到阿里云私服
    String url = aliOSSUtils.upload(image);
    log.info("文件上传完成,访问的地址url{}", url);
    return Result.success(url);
  }
}

5) 测试
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值