Alibaba Cloud OSS activation + configuration and its use

Cloud Storage Solution - Alibaba Cloud OSS

1. Introduction to Alibaba Cloud OSS

​ Alibaba Cloud Object Storage Service (OSS for short) provides you with network-based data access services. Using OSS, you can store and call various unstructured data files including text, pictures, audio and video through the network at any time.
Alibaba Cloud OSS uploads data files to the storage space (bucket) in the form of objects.

​ You can do the following:

  • Create one or more storage spaces, and add one or more files to each storage space.
  • Share and download files by obtaining the address of the uploaded files.
  • Set the corresponding access permissions by modifying the attributes or meta information of the storage space or files.
  • Perform basic and advanced OSS tasks in the Alibaba Cloud management console.
  • Perform basic and advanced OSS tasks using the Alibaba Cloud SDK or making RESTful API calls directly in the application

2. Open OSS

(1) Open https://www.aliyun.com/, apply for an Aliyun account and complete the real-name authentication.

(2) Recharge (you don’t need to do it)

(3) Activate OSS

The first method: click on the link
and click to open: open OSS

The second method: step-by-step activation
Log in to the official website of Alibaba Cloud. Click on the console in the upper right corner.
insert image description here

Move the mouse to the product, find and click Object Storage OSS, and open the OSS product details page. Click Activate Now on the OSS product details page.

insert image description here
A prompt box will pop up, just agree

insert image description here

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

(4)创建存储空间

新建Bucket,命名为 自定义,读写权限为 公共读
按照下面选择就行,主要是红框里面的要选,其他默认就行,都是不开通或者关闭,其中名称自己命名,地址选自己所在区域

insert image description here
insert image description here

(5)上传一张图片,测试是否成功

创建完毕后,在可以进行图片上传测试

扫描文件 ------ 上传文件 -------

insert image description here
insert image description here
insert image description here

在任务列表页面进行查看详情------点击详情后下载图片

insert image description here
insert image description here
insert image description here
insert image description here
下载成功,说明可以访问!!!!

(6)创建AccessKey

insert image description here

insert image description here
insert image description here

继续使用就行,但是注意,这些都是自己的私密资源,要保证自己信息的安全性

insert image description here

3.Java集成OSS

官网参考链接:
https://help.aliyun.com/zh/oss/developer-reference/java-installation

参照官方提供的SDK,改造一下,即可实现文件上传功能:

(1)入门

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.FileInputStream;
import java.io.InputStream;

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

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

        try {
    
    
            InputStream inputStream = new FileInputStream(filePath);
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 设置该属性可以返回response。如果不设置,则返回的response为空。
            putObjectRequest.setProcess("true");
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 如果上传成功,则返回200。
            System.out.println(result.getResponse().getStatusCode());
        } 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();
            }
        }
    }
}

在以上代码中,需要替换的内容为:

  • accessKeyId:阿里云账号AccessKey
  • accessKeySecret:阿里云账号AccessKey对应的秘钥
  • bucketName:Bucket名称
  • objectName:对象名称,在Bucket中存储的对象的名称
  • filePath:文件路径

运行以上程序后,会把本地的文件上传到阿里云OSS服务器上
insert image description here

(2)集成到项目中

1、pom.xml

在Maven工程中使用OSS Java SDK,只需在pom.xml中加入相应依赖即可。以3.15.1版本为例加入如下内容:

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

如果使用的是Java 9及以上的版本,则需要添加jaxb相关依赖。添加jaxb相关依赖示例代码如下:

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

2、application.properties代码:

#自定义的阿里云OSS配置信息
aliyun.oss.endpoint=
aliyun.oss.accessKeyId=
aliyun.oss.accessKeySecret=
aliyun.oss.bucketName=

Introduce the Alibaba Cloud OSS upload file tool class (modified from the official sample code)

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

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

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile multipartFile) throws IOException {
    
    
        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        // 避免文件覆盖
        String originalFilename = multipartFile.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 = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;

        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }
}

3. UploadController code:

import com.itheima.pojo.Result;
import com.itheima.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;

@Slf4j
@RestController
public class UploadController {
    
    

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
    
    
        //调用阿里云OSS工具类,将上传上来的文件存入阿里云
        String url = aliOSSUtils.upload(image);
        //将图片上传完成后的url返回,用于浏览器回显展示
        return Result.success(url);
    }
    
}

4. Use postman to test:

Note: Select --------------
form-data and the value should be selected as file type

insert image description here

おすすめ

転載: blog.csdn.net/AN_NI_112/article/details/132076550