From 0 to 1, apply for cos server and upload pictures to cos file server

Table of Contents

Preparation

Java code writing

Console printing

Organized into tool categories

Write interface

Postman test


Preparation

1. Enter the website address
Tencent Cloud Intelligent Industrial Change·Cloud Shapes the Future – Tencent (tencent.com)

2. Search for cos, click to use it immediately, and it will be given to you for free at the beginning.

3. Storage is based on buckets. First create a bucket and create a folder in the bucket, so click Create Bucket

4. To view the bucket list, click on the left side

5. Click in and create a folder. I have created two folders here.

6. The bucket is finished. To get the secretId secretKey, enter the following address.
Login – Tencent Cloud
Click New Key to create your own key

The above preparation work is completed, let’s test the code below

Java code writing

package com.zsp.quartz.util.OSS;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import java.io.File;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

public class getOSSToken {
        public static void main(String[] args) {

            //Initialize client
            String secretId = "xxxxxx";
            String secretKey = "xxxxxx";
            COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            Region region = new Region("ap-nanjing");
            ClientConfig clientConfig = new ClientConfig(region);
            clientConfig.setHttpProtocol(HttpProtocol.https);
            COSClient cosClient = new COSClient(cred, clientConfig);


            //define bucket
            String bucket = "zsp-image-xxxxxx"; //Bucket name, format: BucketName-APPID

            // upload files
            File localFile = new File("C:/Users/UU/Desktop/My/Life Photos.jpeg");
            //Specify the path to upload the file to COS, that is, the object key.
            String path = "image/" + LocalDateTime.now() + "file" + UUID.randomUUID() + ".jpeg";
            //Three parameters: bucket name, folder path, file
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, path, localFile);
            System.out.println("key is: " + putObjectRequest.getKey()); // image/2023-10-18T11:58:25.792fileef9bb4a9-3b0a-49f1-92a4-5bc3f3572977.jpeg
            //Upload to oss
            cosClient.putObject(putObjectRequest);
            // Get the image address
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            //Three parameters: bucket name, file name, expiration time
            URL url = cosClient.generatePresignedUrl(bucket, putObjectRequest.getKey(), expiration);
            System.out.println(url.toString());

            //Close the resource
            cosClient.shutdown();

        }
}

Console Print

Organize into tool categories

package com.zsp.quartz.util.COS;

import cn.hutool.core.date.DateUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Random;

public class COSUpload {

    private static String secretId = "asdkhjahsdkjhasjkdhas";
    private static String secretKey = "asmdiuoahuihas";
    private static String bucket = "zsp-image-xxxxxxxx";
    private static String fileFolder = "image/";
    private static COSClient cosClient;

    static {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region("ap-nanjing");
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        cosClient = new COSClient(cred, clientConfig);
    }
    public static String uploadFileToCOS(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String substring;
        if (originalFilename.contains(".")) {
            substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        } else {
            substring = originalFilename;
        }
        Random random = new Random();
        String fileName = random.nextInt(10000) + System.currentTimeMillis() + substring;
        InputStream inputStream = null;
        inputStream = file.getInputStream();
        return uploadFileCOS(inputStream, fileName, fileFolder);
    }

    public static String uploadFileCOS(InputStream instream, String fileName, String fileFolder) {
        String ret = "";
        try {
            //Create Metadata of uploaded Object
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            if (fileName.contains(".")) {
                objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            } else {
                objectMetadata.setContentType(getcontentType(fileName));
            }
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            String filePath = fileFolder + DateUtil.format(new Date(), "yyyy/MM/dd") + "/" + fileName;
            // upload files
            PutObjectRequest data = new PutObjectRequest(bucket, filePath, instream, objectMetadata);
            cosClient.putObject(data);

            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            //Three parameters: bucket name, file name, expiration time
            URL url = cosClient.generatePresignedUrl(bucket, data.getKey(), expiration);
            ret = url.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") || FilenameExtension.equalsIgnoreCase(".jpg")
                || FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") || FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") || FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        if (FilenameExtension.equalsIgnoreCase(".pdf")) {
            return "application/pdf";
        }
        return "image/jpeg";
    }
}

Writing interface

/**
     * upload picture
     * @param file
     * @return
     * @throwsException
     */
    private final static int maxSize = 15 * 1024 * 1024;
    @PostMapping("/oss/upload")
    public Result<String> uploadFile(@RequestParam("file")MultipartFile file) throws Exception {
        //Check if the file is empty
        if (file.isEmpty()) return Result.fail("Please select a picture");
        //check file size
        if (file.getSize() > maxSize) return Result.fail("Please upload pictures within 15M");
        final String url = COSUpload.uploadFileToCOS(file);
        ImageResult imageResult = new ImageResult(url);
        return Result.success(url);
    }

Postman test

COS server display

Store in folders based on the creation date of time nodes.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 137749 people are learning the system