Use minio to upload pictures and videos

ps: Because I encountered the use of minio to upload pictures in my business, I will record the use.

  • MinIO is an open source object storage server that can be used to store and retrieve any type of file, including pictures, videos, documents, etc. MinIO is designed to provide high-performance, high-availability, and scalable object storage services while remaining simple to use and low-cost.

  • Why use an object storage server?

    The database can store videos and pictures, but storing a large number of videos and pictures will take up a lot of storage space, causing the database to become large and slow. Furthermore, the main purpose of a database is to store and manage structured data, while videos and pictures are unstructured data, so storing them may require the use of different technologies and tools. Therefore, it is often recommended to store videos and pictures in a dedicated file system or cloud storage, rather than directly in a database.

  • Key features of MinIO include:

    1. High performance: MinIO is written in Go language and adopts some optimization technologies, such as concurrency and asynchronous I/O, to achieve high-performance object storage services.

    2. High availability: MinIO supports mechanisms such as multi-copy replication and failover, which can ensure the reliability and availability of data.

    3. Scalability: MinIO adopts a distributed architecture and can expand storage capacity and throughput by adding new nodes.

    4. Simple and easy to use: MinIO provides simple and easy-to-use API and command line tools, which can facilitate the management and operation of object storage.

    5. Low cost: MinIO can run on standard hardware devices and does not require special storage devices, which can reduce storage costs.

    MinIO supports multiple APIs and protocols, including S3, NFS, HDFS, Azure Blob Storage, etc., and can be integrated with various applications and systems. In addition, MinIO also provides some advanced functions, such as object locking, version control, event notification, etc., to meet different business needs.

    In short, MinIO is a powerful, high-performance, easy-to-use and low-cost object storage server suitable for application scenarios of all sizes. Alibaba Cloud and Tencent Cloud seem to charge for 10G oss. I think they can be used and the operation is not difficult.

  • When using MinIO's Java SDK, you need to provide the following four parameters:

    1. ENDPOINT: The address of the MinIO server, including protocol, host name and port number. For example, http://localhost:9000represents a locally running MinIO server.

    2. ACCESS_KEY: Access key, used for authentication. In MinIO, each user has an access key and a secret key used to access and manage buckets and objects.

    3. SECRET_KEY: Secret key, used for authentication. Used with access keys to access and manage buckets and objects.

    4. BUCKET_NAME: The name of the bucket used to store and manage objects. In MinIO, each bucket has a unique name.

  • ackage com.atguigu.gmall.product.controller;
    
    import com.atguigu.gmall.common.result.Result;
    import io.minio.BucketExistsArgs;
    import io.minio.MakeBucketArgs;
    import io.minio.MinioClient;
    import io.minio.PutObjectArgs;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.util.UUID;
    
    /**
     * @author 罗峰
     * @version 1.0
     * @description TODO
     * @date 2023-05-07 15:24
     */
    @RestController
    @RequestMapping("admin/product")
    public class FileUploadController {
    
        //  获取文件上传对应的地址
        @Value("${minio.endpointUrl}")
        public String endpointUrl;
    
        @Value("${minio.accessKey}")
        public String accessKey;
    
        @Value("${minio.secreKey}")
        public String secreKey;
    
        @Value("${minio.bucketName}")
        public String bucketName;
    
        //  文件上传控制器
        @PostMapping("fileUpload")
        public Result fileUpload(MultipartFile file) throws Exception{
            //  准备获取到上传的文件路径!
            String url = "";
    
            // 使用MinIO服务的URL,端口,Access key和Secret key创建一个MinioClient对象
            // MinioClient minioClient = new MinioClient("https://play.min.io", "Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(endpointUrl)
                            .credentials(accessKey, secreKey)
                            .build();
            // 检查存储桶是否已经存在
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if(isExist) {
                System.out.println("Bucket already exists.");
            } else {
                // 创建一个名为asiatrip的存储桶,用于存储照片的zip文件。
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(bucketName)
                        .build());
            }
            //  定义一个文件的名称 : 文件上传的时候,名称不能重复!
            String fileName = System.currentTimeMillis()+ UUID.randomUUID().toString();
            // 使用putObject上传一个文件到存储桶中。
            //  minioClient.putObject("asiatrip","asiaphotos.zip", "/home/user/Photos/asiaphotos.zip");
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            //  System.out.println("/home/user/Photos/asiaphotos.zip is successfully uploaded as asiaphotos.zip to `asiatrip` bucket.");
            //  文件上传之后的路径: http://39.99.159.121:9000/gmall/xxxxxx
            url = endpointUrl+"/"+bucketName+"/"+fileName;
    
            System.out.println("url:\t"+url);
            //  将文件上传之后的路径返回给页面!
            return Result.ok(url);
        }
    }
    

    The image is passed from the front end. We use MultipartFile file to receive it. After uploading it to minio, we need to pass the generated path to the front end page for display, but the path is also passed to the database.

  • Transferring pictures and videos is similar, but if the video involves resuming the upload business, it will be a bit complicated.

  • Summarize:

  • 1. Import minio dependencies

  • 2. Write the configuration file, four parameters, and inject them into the layer that handles the business with the @Value annotation.

  • 3. Create a client object, pass in the parameters, and then determine whether the bucket exists. If not, create it.

  • 4. Call the putObject method to upload images

  • 5. Return the path to the front-end ps: a large dto is used in the database. The object is saved, and the component for uploading images is only a part of the form. We pass the entire form.

Guess you like

Origin blog.csdn.net/weixin_65379795/article/details/130586959