10 minutes to learn Ali OSS object storage

I. Introduction

Recently, many friends have asked, what should we do if we want to store large-scale files?

In fact, there are many technologies for file storage. If we search the Internet, you will find that there are various technologies. For example, there is a technology called FastDFS that can realize file storage, but this solution requires a self-built server, which is very troublesome.

In fact, many companies are now using Tencent Cloud or Alibaba Cloud technology. For example, Alibaba Cloud provides OSS object storage technology. This technology is safe, reliable and easy to use. It only takes 10 minutes to get started with storage. What? You do not believe? ! Then follow Brother Jian step by step, if Brother Jian takes you 10 minutes to complete the file storage, you can give me a thumbs up!

2. Analysis of the role of OSS object storage

Before learning the specific implementation of OSS, let's briefly understand what OSS is.

Aliyun object storage OSS, simply put, we spend money to buy a piece of storage space in Alibaba, and then we can store various file resources such as pictures, audio, video, etc. on the object storage OSS server. Then the object storage OSS server can upload, download, and delete these files for authorized personnel.

So with OSS, we save a series of tedious operations such as purchasing hardware storage servers, building storage servers, and operating and managing storage servers.

With these basic understandings, we can start using OSS. Of course, first we have to buy OSS service!

3. Object storage OSS registration and configuration

Alibaba Cloud Object Storage OSS official website address:

Object Storage OSS_Cloud Storage Service_Enterprise Data Management_Storage-Alibaba Cloud

3.1 Registration and login

After entering the official website of Alibaba Cloud, the first thing is to register and log in. We can log in with our Alipay account, scan the code on the Aliyun mobile client, or log in with the account password. In short, Alibaba Cloud provides multiple login methods. Basically, Alipay's products can be used universally with your own Alipay account.

3.2 Activate the object storage OSS service

First, we find Alibaba Cloud's object storage OSS service and click to enter.

image.png

Click the Activate button to activate the object storage OSS service.

image.png

3.3 Management Console

After registering, logging in, and activating the OSS service, click the management console to enter the console interface.

image.png

Then enter the console interface.

image.png

Here we need to create a Bucket first, click the Bucket list menu, click the Create Bucket button, and then fill in the following content. Everyone should pay attention that the name of the Bucket must be unique and cannot be repeated.

image.png

image.png

3.4 Upload pictures using the console

After the bucket is created, we can use the console to upload files for testing. The upload operation is as follows:

image.png

The result of successfully uploading a picture is as follows:

image.png

4. Code implementation

Of course, when we are developing, we will definitely not upload files manually in this way, mainly using code to implement.

4.1 Build the project environment

Let's create a project first, the name is aliyunossDemo. Here we are of course using Maven to create projects. Remember not to choose to use the skeleton that comes with Maven.

Next import dependent packages in pom.xml.

<!-- 继承Spring boot工程 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
</parent>

<properties>
    <!-- 项目源码及编译输出的编码 -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <!-- 项目编译JDK版本 -->
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>

    <!-- 依赖包版本管理 -->
    <spring.boot.version>2.1.5.RELEASE</spring.boot.version>
    <aliyun-oss-version>3.10.2</aliyun-oss-version>
    <httpcore-verison>4.4.3</httpcore-verison>
    <httpclient-version>4.5.1</httpclient-version>
</properties>

<dependencies>
    <!-- Spring boot starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>${spring.boot.version}</version>
    </dependency>
    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
        <version>${aliyun-oss-version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>${httpcore-verison}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>${httpclient-version}</version>
    </dependency>
</dependencies>
注意,如果你的JDK是1.9或者以上版本,需要加入jaxb相关依赖,其他JDK版本不需要!

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>

<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>

<!-- no more than 2.3.3-->
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.3</version>
</dependency>

然后我们在resources目录下创建一个application.yml配置文件。
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
  application:
    name: aliyun-oss-demo
server:
  port: 9001
aliyun:
  oss:
    #服务器地址, 我选择的是华北2-北京地址如下
    endpoint: http://oss-cn-beijing.aliyuncs.com
    #子账户名称,在自己控制台账户的Access中查看
    accessKeyId: 填写自己的accessKey
    #子账户密码
    accessKeySecret: 填写自己的accessSecret
    #自己创建的桶的名字
    bucketName: qianfeng-file
   

 接着我们创建一个启动类AliyunOssApplication。
package com.qianfeng;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 微服务启动类
 * @Author 千锋健哥
 */
@SpringBootApplication
public class AliyunOssApplication {

    public static void main(String[] args) {
        SpringApplication.run(AliyunOssApplication.class, args);
    }
}

4.2 Encapsulation tools

Create the com.qianfeng.util package and put it into the file operation tool class AliyunOSSUtil.

package com.qianfeng.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Date;

/**
 * 阿里云OSS上传,下载, 删除文件工具类
 * @Author 千锋健哥
 */
public class AliyunOSSUtil {

    /**
     * byte数组格式上传文件
     * @param endpoint          OSS对外服务的访问域名
     * @param accessKeyId       accessKey账号
     * @param accessKeySecret   accessKey密码
     * @param bucketName        桶名字
     * @param objectName        完整文件名, 例如abc/efg/123.jpg
     * @param content           文件内容, byte数组格式
     * @Author 千锋健哥
     */
    public static void uploadByByteArrayFile(String endpoint,
                                             String accessKeyId,
                                             String accessKeySecret,
                                             String bucketName,
                                             String objectName,
                                             byte[] content) throws Exception {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //创建上传请求对象
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content));

        // 上传
        PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();
    }

    /**
     * 输入流格式上传文件
     * @param endpoint          OSS对外服务的访问域名
     * @param accessKeyId       accessKey账号
     * @param accessKeySecret   accessKey密码
     * @param bucketName        桶名字
     * @param objectName        完整文件名, 例如abc/efg/123.jpg
     * @param content           文件内容, 输入流格式
     * @Author 千锋健哥
     */
    public static void uploadByInputStreamFile(String endpoint,
                                               String accessKeyId,
                                               String accessKeySecret,
                                               String bucketName,
                                               String objectName,
                                               InputStream content) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传
        ossClient.putObject(bucketName, objectName, content);
        // 关闭OSSClient
        ossClient.shutdown();
    }

    /**
     * byte数组格式上传文件并返回上传后的URL地址
     * @param endpoint          OSS对外服务的访问域名
     * @param accessKeyId       accessKey账号
     * @param accessKeySecret   accessKey密码
     * @param bucketName        桶名字
     * @param objectName        完整文件名, 例如abc/efg/123.jpg
     * @param content           文件内容, byte数组格式
     * @Author 千锋健哥
     */
    public static String uploadImage(String endpoint,
                              String accessKeyId,
                              String accessKeySecret,
                              String bucketName,
                              String objectName,
                              byte[] content)  throws Exception {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建上传文件的元信息,可以通过文件元信息设置HTTP header(设置了才能通过返回的链接直接访问)。
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/jpg");
        // 文件上传
        ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content), objectMetadata);
        // 设置URL过期时间为1小时。
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
        //返回url地址
        String url = ossClient.generatePresignedUrl(bucketName, objectName, expiration).toString();
        //关闭OSSClient。
        ossClient.shutdown();
        return url;
    }

    /**
     * 下载文件到本地
     * @param endpoint          OSS对外服务的访问域名
     * @param accessKeyId       accessKey账号
     * @param accessKeySecret   accessKey密码
     * @param bucketName        桶名字
     * @param objectName        完整文件名, 例如abc/efg/123.jpg
     * @param localFile         下载到本地文件目录
     * @Author 千锋健哥
     */
    public static void downFile(String endpoint,
                                String accessKeyId,
                                String accessKeySecret,
                                String bucketName,
                                String objectName,
                                String localFile) throws Exception {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
        ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFile));

        // 关闭OSSClient。
        ossClient.shutdown();
    }

    /**
     * 删除文件
     * @param endpoint          OSS对外服务的访问域名
     * @param accessKeyId       accessKey账号
     * @param accessKeySecret   accessKey密码
     * @param bucketName        桶名字
     * @param objectName        完整文件名, 例如abc/efg/123.jpg
     * @Author 千锋健哥
     */
    public static void deleteFile(String endpoint,
                                  String accessKeyId,
                                  String accessKeySecret,
                                  String bucketName,
                                  String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 删除文件。如需删除文件夹,请将ObjectName设置为对应的文件夹名称。如果文件夹非空,则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject(bucketName, objectName);

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}

4.3 Case of uploading files

We implement file upload in Controller.

package com.qianfeng.controller;

import com.qianfeng.util.AliyunOSSUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件管理接口
 * 提供文件各种形式上传, 下载, 删除等操作
 * @Author 千锋健哥
 */
@RestController
@RequestMapping("/file")
public class FileManagerController {

    //OSS服务器访问域名
    @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;

    /**
     * byte数组形式上传
     * @param file
     * @Author 千锋健哥
     */
    @PostMapping("/upload1")
    public void upload(@RequestParam("file") MultipartFile file) throws Exception {
        AliyunOSSUtil.uploadByByteArrayFile(endpoint, accessKeyId, accessKeySecret, bucketName, file.getOriginalFilename(), file.getBytes());
    }
    
    /**
     * 输入流形式上传
     * @param file
     * @Author 千锋健哥
     */
    @PostMapping("/upload2")
    public void upload2(@RequestParam("file") MultipartFile file) throws Exception {
        AliyunOSSUtil.uploadByInputStreamFile(endpoint, accessKeyId, accessKeySecret, bucketName, file.getOriginalFilename(), file.getInputStream());
    }
}

4.4 Case of uploading pictures and returning access path

In this case, we show you how to obtain the returned access path.

/**
 * 上传图片并返回上传后的URL地址
 * @param file
 * @Author 千锋健哥
 */
@PostMapping("/upload3")
public String upload3(@RequestParam("file") MultipartFile file) throws Exception {
    String url = AliyunOSSUtil.uploadImage(endpoint, accessKeyId, accessKeySecret, bucketName, file.getOriginalFilename(), file.getBytes());
    System.out.println("===千锋健哥===" + url);
    return url;
}

4.5 Cases of deleting files

This is an example of deleting uploaded files.

/**
 * 删除文件
 * @param objName 需要删除的对象名称
 * @Author 千锋健哥
 */
@DeleteMapping("/delete")
public void deleteFile(String objName) {
    AliyunOSSUtil.deleteFile(endpoint, accessKeyId, accessKeySecret, bucketName, objName);
}

Qianfeng Education Java Introduction Full Set of Video Tutorials (java core technology, suitable for java zero foundation, necessary for self-study of Java)

Guess you like

Origin blog.csdn.net/longz_org_cn/article/details/132201619