JAVAEE Look at the framework 19-Seven Niuyun (including tools)

1. Picture storage solution

In actual development, we will have many servers that handle different functions. For example:
Application server: responsible for deploying our application
Database server: running our database
File server: server responsible for storing user uploaded files

The purpose of sub-server processing is to let the server do its job, so as to improve the operational efficiency of our project.
Common image storage solutions:
Solution 1: Use nginx to build a picture server, the API is not friendly and cannot be distributed
Solution 2: Use an open source distributed file storage system, such as Fastdfs, HDFS, S3, CEPH, etc.

Solution 3: Use cloud storage, such as Alibaba Cloud, Qiniu Cloud, etc.

2. Picture storage solution_Qiniu Cloud Storage

Seven cattle cloud (seven cattle under the Shanghai Information Technology Co., Ltd.) is a leading visual data intelligence and intelligence-core
enterprise-class cloud computing service providers the heart, but also the well-known intelligent video cloud service providers, accumulated more than 70 million Companies
provide services, covering 80% of domestic netizens. Around the rich media scene, we launched object storage, converged CDN acceleration, container
cloud, big data platform, deep learning platform and other products, and provided a one-stop intelligent video cloud solution.
Provide a sustainable and intelligent video cloud ecosystem for various industries and applications, help enterprises quickly go to the cloud, and create broader commercial
value.
Official website: https://www.qiniu.com/
Through Qiniuyun's official website, we can know that it provides a variety of services. We mainly use the
object storage service provided by Qiniuyun to store pictures.

1. To use Qiniu Cloud's services, you first need to register as a member. Address: https://portal.qiniu.com/signup

After the registration is completed, you can log in to Qiniuyun using the email and password you just registered.

2. After successful login, click the management console in the upper right corner of the page. Note: After successful login, real-name authentication is required to perform related operations.

3. Create and view storage space

To store pictures, we need to create a new storage space in the Qiniu cloud management console. Click the
Add Now button under Object Storage on the home page of the management console , and the page jumps to the New Storage Space page.

Storage space domain name 30-day expiration period

4. Authentication

You can learn how to operate the Qiniu Cloud service through the developer center provided by Qiniu Cloud,
https://developer.qiniu.com/

Click Object Storage, jump to the Object Storage Development page, address: https://developer.qiniu.com/kodo Qiniu
Cloud provides a variety of ways to operate object storage services, this project uses the Java SDK method,
address:

https://developer.qiniu.com/kodo/sdk/1239/java

To use the Java SDK to operate Qiniu Cloud, you need to import the following maven coordinates:

<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu‐java‐sdk</artifactId>
<version>7.2.0</version>
</dependency>
<dependency>
  <groupId>com.qiniu</groupId>
  <artifactId>qiniu-java-sdk</artifactId>
  <version>[7.2.0, 7.2.99]</version>
</dependency>

Here, versiona version range is specified. Each update pom.xmlwill try to download 7.2.xthe latest version of the version. You can manually specify a fixed version.

5. Manual download

All functions of the Java SDK require legal authorization. The signing of the authorization certificate requires a pair of
valid Access Key and Secret Key under the Qiniu account , which can be found in the personal center of the Qiniu cloud management console
(https://portal.qiniu.com/user/ key), as shown below:

[External chain image transfer failed, the source site may have an anti-theft chain mechanism, it is recommended to save the image and upload it directly (img-mDYZYD8s-1587296014587) (img \ 2.png)]

6. Use the SDK provided by Qiniu Cloud to upload files

New picture:

@Test
    public void test1(){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
        String accessKey = "dulF9Wze9bxujtuRvu3yyYb9JX1Sp23jzd3tO708";
        String secretKey = "vZkhW7iot3uWwcWz9vXfbaP4JepdWADFDHVLMZOe";
        String bucket = "health-2019-57";
//如果是Windows情况下,格式是 D:\\qiniu\\test.png
        String localFilePath = "D:\\教学\\课程资料\\传智健康-加密\\视频\\day04\\讲义\\img\\1.png";
//默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = "test-1.png";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            //jackson fastjson gson json对象转换成JAVA对象
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

7. Use the SDK provided by Qiniu Cloud to delete files

Delete picture

 //删除七牛云服务器中的图片
    @Test
    public void test2(){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        String accessKey = "dulF9Wze9bxujtuRvu3yyYb9JX1Sp23jzd3tO708";
        String secretKey = "vZkhW7iot3uWwcWz9vXfbaP4JepdWADFDHVLMZOe";
        String bucket = "itcasthealth_space_1";
        String key = "test-1.lng";
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException ex) {
            //如果遇到异常,说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }

Pay special attention to the choice of zone:

engine room Zone object
East China Zone.zone0()
North China Zone.zone1()
South China Zone.zone2()
Kitami Zone.zoneNa0()
Southeast Asia Zone.zoneAs0()

8. Packaging tools

package com.ittest.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * 七牛云工具类
 */
public class QiniuUtils {
    public  static String accessKey = "dulF9Wze9bxujtuRvu3yyYb9JX1Sp23jzd3tO708";
    public  static String secretKey = "vZkhW7iot3uWwcWz9vXfbaP4JepdWADFDHVLMZOe";
    public  static String bucket = "itcasthealth_space_1";

    public static void upload2Qiniu(String filePath,String fileName){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(filePath, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException ex) {
            Response r = ex.response;
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    //上传文件
    public static void upload2Qiniu(byte[] bytes, String fileName){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果
            //"{\"key":\"value"}"
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    //删除文件
    public static void deleteFileFromQiniu(String fileName){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        String key = fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException ex) {
            //如果遇到异常,说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }
}

Published 78 original articles · won praise 30 · views 3624

Guess you like

Origin blog.csdn.net/ZMW_IOS/article/details/105620600