Home Java javaTutorial How to use Java and Qiniu Cloud KODO for object storage and management

How to use Java and Qiniu Cloud KODO for object storage and management

Jul 06, 2023 pm 08:01 PM
java object storage manage Qiniuyun

How to use Java and Qiniu Cloud KODO for object storage and management

1. Introduction
With the rapid development of cloud computing and big data, cloud storage has become an increasingly important part. Qiniu Cloud KODO, as a well-known object storage platform in China, provides powerful storage and management functions and is widely used in websites, mobile applications, live video and other fields. This article will introduce how to use Java and Qiniu Cloud KODO for object storage and management, and give corresponding code examples.

2. Create Qiniu Cloud account and storage space

  1. Visit Qiniu Cloud official website (https://www.qiniu.com/) and click the "Register" button to create an account .
  2. Log in to Qiniu Cloud Console and create a storage space. On the "Storage Space" page of the console, click "New Space", fill in the corresponding information and save it. Here, the storage space is named "mybucket" as an example.

3. Add dependent libraries
Add the following dependent libraries in the pom.xml file of the Java project:

<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>7.4.0</version>
</dependency>
Copy after login

4. Configure Qiniu Cloud access key
Add the access key of Qiniu Cloud in the configuration file of the Java project, as shown below:

qiniu.accessKeyId=your_access_key_id
qiniu.secretKey=your_secret_key
qiniu.bucket=mybucket
qiniu.domain=http://your_domain_url
Copy after login

5. Upload the file to Qiniu Cloud KODO

  1. Create a file named QiniuUtils Tool class, and add the following code:
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

public class QiniuUtils {
    private static final String ACCESS_KEY = ConfigUtil.getProperty("qiniu.accessKeyId");
    private static final String SECRET_KEY = ConfigUtil.getProperty("qiniu.secretKey");
    private static final String BUCKET_NAME = ConfigUtil.getProperty("qiniu.bucket");
    private static final String DOMAIN = ConfigUtil.getProperty("qiniu.domain");

    // 上传文件到七牛云KODO
    public static String uploadFile(String filePath) throws IOException {
        String key = UUID.randomUUID().toString(); // 自动生成唯一的key
        String uploadToken = getUploadToken(); // 获取上传凭证

        OkHttpClient client = new OkHttpClient();
        // 读取文件内容
        byte[] data = Files.readAllBytes(Paths.get(filePath));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), data);

        // 构建请求
        Request request = new Request.Builder()
                .url("http://upload.qiniu.com/putb64/" + -1 + "/key/" + UrlSafeBase64.encodeToString(key))
                .header("Content-Type", "application/octet-stream")
                .header("Authorization", "UpToken " + uploadToken)
                .post(requestBody)
                .build();

        // 发送请求
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            JSONObject jsonObject = new JSONObject(response.body().string());
            String url = DOMAIN + "/" + jsonObject.getString("key");
            return url;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    // 获取上传凭证
    private static String getUploadToken() {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        return auth.uploadToken(BUCKET_NAME);
    }
}
Copy after login
  1. Call the QiniuUtils.uploadFile() method where the file needs to be uploaded, as shown below:
public class MainApp {
    public static void main(String[] args) throws IOException {
        String filePath = "path/to/file.jpg";
        String url = QiniuUtils.uploadFile(filePath);
        System.out.println("上传成功,文件URL为:" + url);
    }
}
Copy after login

6. Download the file

  1. Add the following code in the QiniuUtils class:
// 下载文件
public static void downloadFile(String key, String savePath) throws IOException {
    String downloadUrl = DOMAIN + "/" + key;
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(downloadUrl)
            .build();
    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        byte[] data = response.body().bytes();
        Files.write(Paths.get(savePath), data);
        System.out.println("下载成功,文件保存路径为:" + savePath);
    } else {
        throw new IOException("Unexpected code " + response);
    }
}
Copy after login
  1. Call the QiniuUtils.downloadFile() method where the file needs to be downloaded, as follows Display:
public class MainApp {
    public static void main(String[] args) throws IOException {
        String key = "file.jpg";
        String savePath = "path/to/save/file.jpg";
        QiniuUtils.downloadFile(key, savePath);
    }
}
Copy after login

7. Delete files
Add the following code in the QiniuUtils class:

// 删除文件
public static void deleteFile(String key) throws IOException {
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    Configuration cfg = new Configuration(Zone.zone0());
    BucketManager bucketManager = new BucketManager(auth, cfg);
    bucketManager.delete(BUCKET_NAME, key);
    System.out.println("删除成功");
}
Copy after login

Call the QiniuUtils.deleteFile() method where the file needs to be deleted, as follows Display:

public class MainApp {
    public static void main(String[] args) throws IOException {
        String key = "file.jpg";
        QiniuUtils.deleteFile(key);
    }
}
Copy after login

The above is an introduction and sample code on how to use Java and Qiniu Cloud KODO for object storage and management. Through these codes, we can easily upload, download and delete files, and implement basic operations on cloud storage. Hope this article helps you!

The above is the detailed content of How to use Java and Qiniu Cloud KODO for object storage and management. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

How to add and manage users in Google Manager How to add and manage users in Google Manager Sep 02, 2024 pm 02:41 PM

How to add and manage users in Google Manager? Google Chrome supports multiple users to log in, so we don’t have to worry about logging in across devices. If we have many users, we need to add management. Some friends may not know how to operate. Don't worry, the editor has compiled a detailed step-by-step tutorial for everyone today. If you are interested, come and take a look with the editor. Detailed step-by-step tutorial instructions 1. After turning on the computer, find the installed Google Chrome icon on the desktop and double-click to open it, as shown in the picture below. 2. Click the three dots icon in the upper right corner of Google Chrome, as shown in the picture below. 3. Click the [Settings] option in the drop-down menu of Google Chrome, as shown in the figure below. 4. In the Google Chrome settings interface that opens, click [Manage ch

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles