This article introduces how to use Java API to operate ali Cloud OSS object storage.

1. Console operations

First introduce some basic concepts of Ali Cloud OSS object storage.

1.1 Going to the Object Storage Page

Log in to aliyun and enter the object storage interface, as shown in the figure.

After entering, the following figure is displayed.

1.2 Basic Concepts of OSS

Here is not more about how to upload and download files in Ali cloud, these operations can be found basically point by point.

1.2.1 the Bucket

Bucket is essentially a storage space of ali Cloud OSS object storage, which can be understood as a disk according to the understanding of computers (I don’t know if the analogy is appropriate).

Creating a bucket is simple, as shown in the figure below.

Note that different partitions have different endpoints, which will be used in subsequent API usage. The storage type and read/write permission Settings are based on your own conditions. This section uses standard storage and private permission Settings as an example.

1.2.2 the AccessKey

AccessKey is the Secret Key to Access ali Cloud API. Here we also need to create a copy in advance. After creating it, we need to remember our AccessKey ID and AccessKey Secret.

2 API

2.1 API address

Generally, object storage is used to upload and download files. The full API address is as follows:

Help.aliyun.com/document_de…

2.2 PREPARATIONS for API Use

Java is very simple to use. Reference dependencies directly in Maven as follows:

< the dependency > < groupId > com. Aliyun. Oss < / groupId > < artifactId > aliyun - SDK - oss < / artifactId > < version > 2.8.3 < / version > </dependency>Copy the code

2.3 Building an OSSClient Instance

This is where the endpoint and AccessKey we mentioned above are used, and the contents of the build instance are shown below.

// Endpoint This section uses Hangzhou as an example. Enter other regions based on actual conditions. String endpoint ="http://oss-cn-beijing.aliyuncs.com"; // Use the newly created accessKeyId and accessKeySecret String accessKeyId ="<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>"; // Create an OSSClient instance. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); // Todo performs operations on OSS // closes OSSClient. ossClient.shutdown();Copy the code

2.4 Uploading files

There are two common ways to upload files. One is to return the address where you can view the file, and the other is to download the file directly through the address.

2.4.1 Uploading a file returns the address where the image can be previewed

Uploading files has some caveats:

  • 1. Do not repeat the file name; otherwise, the file name will be overwritten.
  • 2. You are advised to create a folder for files of different dates.

Here to upload an image of a local desktop, for example, after the upload in Bucket automatically created date format yyyyMMdd folder to store the file, the file name in the form of current timestamp with random number of joining together, as a result of the returned URL is with signature information, so here temporarily set the expiration time for one hour, if you need can be longer.

The full content is as follows:

package com.dalaoyang.upload;

import com.aliyun.oss.OSSClient;

import java.io.File;
import java.net.URL;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AliyunUpload {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAIRr3alAhROGTA";
        String accessKeySecret = "* * * * * *";
        String fileName = "/Users/dalaoyang/Desktop/aliyun.jpeg";
        String bucketName = "dalaoyang-test"; String suffixName = filename.substring (filename.lastIndexof ())".")); String finalFileName = System.currentTimemillis () +"" + new SecureRandom().nextInt(0x0400) + suffixName;
        String objectName = sdf.format(new Date()) + "/"+ finalFileName; File file = new File(fileName); OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); ossClient.putObject(bucketName, objectName, file); // Set the URL expiration time to 1 hour. Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000); // Generate a signature URL that is accessed by the GET method. Visitors can access related content directly through the browser. URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration); ossClient.shutdown(); System.out.println(url.toString()); }}Copy the code

The return address format is as follows:

http://dalaoyang-test.oss-cn-beijing.aliyuncs.com/20190518/1558155342968407.jpeg?Expires=1558158948&OSSAccessKeyId=LTAIR r3alAhROGTA&Signature=%2BIjVpD%2BTWrRmSt4kU7axo6Cnqbw%3DCopy the code

Browser access looks like this:

Check the figure shown in Ali Cloud OSS, and you can see that the folder is also created.

2.4.2 Uploading files, return to the address where you can download pictures directly

If you want to return an address where you can download directly, just set the file contentDisposition to attachment; The complete content is as follows:

package com.dalaoyang.upload;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;

import java.io.File;
import java.net.URL;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AliyunUpload {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAIRr3alAhROGTA";
        String accessKeySecret = "* * * * * *";
        String fileName = "/Users/dalaoyang/Desktop/WechatIMG4.png";
        String bucketName = "dalaoyang-test"; String suffixName = filename.substring (filename.lastIndexof ())".")); String finalFileName = System.currentTimemillis () +"" + new SecureRandom().nextInt(0x0400) + suffixName;
        String objectName = sdf.format(new Date()) + "/" + finalFileName;
        File file = new File(fileName);

        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentDisposition("attachment;"); OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); ossClient.putObject(bucketName, objectName, file, meta); // Set the URL expiration time to 1 hour. Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000); // Generate a signature URL that is accessed by the GET method. Visitors can access related content directly through the browser. URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration); ossClient.shutdown(); System.out.println(url.toString()); }}Copy the code

This time the returned address downloads the file directly from the browser.

3 summary

Ali cloud OSS operation or there are a lot of gameplay, such as upload and download with progress bar, section upload and so on, if you need to play according to the scene.