zoukankan      html  css  js  c++  java
  • 使用Java写一个minio的客户端上传下载文件

    前言:

      确保已经安装了minio的服务端

    代码:

    pom.xml

    <dependency>
        <groupId>io.minio</groupId>
        <artifactId>minio</artifactId>
        <version>7.0.2</version>
    </dependency>

    application.yml

    server:
    port:90
    minio: url: http:
    //10.69.94.140:9000 accessKey: 账号 secretKey: 密码 defaultFolder: /

    MinioProperties.java

    @ConfigurationProperties("minio")
    @Data
    public class MinioProperties {
        private String url;
        private String accessKey;
        private String secretKey;
        private String defaultFolder;
    }

    SpringConfig.java

    @Configuration
    @EnableConfigurationProperties(MinioProperties.class)
    @Slf4j
    public class SpringConfig {
        @Autowired
        private MinioProperties minioProperties;
    
        @Bean
        public MinioClient minioClient() {
            try {
                return new MinioClient(minioProperties.getUrl(), minioProperties.getAccessKey(), minioProperties.getSecretKey());
            } catch (Exception e) {
                log.error(e.toString());
            }
            return null;
        }
    
    }

    ImagesController.java

    @RestController
    @RequestMapping("/image")
    @Slf4j
    @CrossOrigin(origins = "*")
    public class ImageController {
    
        @Autowired
        private FileService fileService;
    
        /*******
         * Get image file, this method return an image type file which can be displayed in browser.
         * @param bucketName, system, each system should belong a special bucket.
         * @param category, a system may contain multiple category
         * @param fileName
         */
        @GetMapping(value = "/get/{bucketName}/{category}/{objectName}/{fileName}", produces = MediaType.IMAGE_JPEG_VALUE)
        public byte[] get(@PathVariable("bucketName") String bucketName, @PathVariable("category") String category,
                          @PathVariable("objectName") String objectName,
                          @PathVariable("fileName") String fileName) throws Exception {
            return fileService.getFile(bucketName, category, objectName);
        }
    
        @GetMapping("/download/{bucketName}/{category}/{objectName}/{fileName}")
        public void download(@PathVariable("bucketName") String bucketName, @PathVariable("category") String category,
                             @PathVariable("objectName") String objectName,
                             @PathVariable("fileName") String fileName, HttpServletResponse response) throws Exception {
            byte[] buffer = fileService.getFile(bucketName, category, objectName);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-disposition", "attachment; filename="" + fileName + """);
            response.getOutputStream().write(buffer);
            response.flushBuffer();
            response.getOutputStream().close();
        }
    
        @PostMapping("/upload/{bucketName}/{category}")
        public String upload(@PathVariable("bucketName") String bucketName, @PathVariable("category") String category,
                             @RequestParam("file") MultipartFile file) throws Exception {
            String objectName = UUID.randomUUID().toString();
            fileService.storeFile(bucketName, category, objectName, file.getBytes());
            return String.format("image/get/%s/%s/%s/%s", bucketName, category, objectName, file.getOriginalFilename());
        }
    }

    FilesController.java

    @RestController
    @RequestMapping("/files")
    @Slf4j
    @CrossOrigin(origins = "*")
    public class FilesController {
    
        @Autowired
        private FileService fileService;
    
        @GetMapping("/download/{bucketName}/{category}/{objectName}/{fileName}")
        public void download(@PathVariable("bucketName") String bucketName, @PathVariable("category") String category,
                             @PathVariable("objectName") String objectName, @PathVariable("fileName") String fileName, HttpServletResponse response) throws Exception {
            byte[] buffer = fileService.getFile(bucketName, category, objectName);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-disposition", "attachment; filename="" + fileName + """);
            response.getOutputStream().write(buffer);
            response.flushBuffer();
            response.getOutputStream().close();
        }
    
        @PostMapping("/upload/{bucketName}/{category}")
        public String upload(@PathVariable("bucketName") String bucketName, @PathVariable("category") String category,
                             @RequestParam("file") MultipartFile file) throws Exception {
            String objectName = UUID.randomUUID().toString();
            fileService.storeFile(bucketName, category, objectName, file.getBytes());
            return String.format("files/download/%s/%s/%s/%s", bucketName, category, objectName, file.getOriginalFilename());
        }
    }

      

    FileService.java

    import com.google.common.io.ByteStreams;
    import io.minio.MinioClient;
    import io.minio.ObjectStat;
    import io.minio.PutObjectOptions;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    
    /**
     * @author zengsam
     */
    @Service
    @Slf4j
    public class FileService {
        @Autowired
        private MinioClient minioClient;
    
        /********
         * Get file binary, generally, this file should be readable by browser.
         * @param bucketName
         * @param category
         * @param fileName
         * @return
         * @throws Exception
         */
        public byte[] getFile(String bucketName, String category, String fileName) throws Exception {
            String objectName = getObjectName(category, fileName);
            ObjectStat stat = minioClient.statObject(bucketName, objectName);
            int length = (int) stat.length();
            try (InputStream inputStream = minioClient.getObject(bucketName, objectName);
                 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(length)) {
                ByteStreams.copy(inputStream, outputStream);
                byte[] buffer = outputStream.toByteArray();
                return buffer;
            } catch (Exception e) {
                log.error(e.toString());
            }
    
            return new byte[0];
        }
    
        /*******
         * Stroe file to min io
         * @param bucketName
         * @param category
         * @param fileName
         * @param buffer
         * @return
         */
        public boolean storeFile(String bucketName, String category, String fileName, byte[] buffer) {
            String objectName = getObjectName(category, fileName);
            checkBucketName(bucketName);
            try (InputStream inputStream = new ByteArrayInputStream(buffer)) {
                PutObjectOptions options = new PutObjectOptions(buffer.length, -1);
                minioClient.putObject(bucketName, objectName, inputStream, options);
                return true;
            } catch (Exception e) {
                log.error(e.toString());
            }
    
            return false;
        }
    
        /*****
         * Check existence of bucket, create it if it doesn't
         * @param bucketName
         */
        private void checkBucketName(String bucketName) {
            try {
                if (minioClient.bucketExists(bucketName)) {
                    return;
                }
    
                log.info("Bucket {} doesn't exist, create", bucketName);
                minioClient.makeBucket(bucketName);
            } catch (Exception e) {
                log.error(e.toString());
            }
    
        }
    
        private String getObjectName(String category, String fileName) {
            return category + "/" + fileName;
        }
    }

    upload.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Upload file test</title>
    </head>
    <body>
        <form action="http://localhost:90/image/upload/zeng/test" method="post" enctype="multipart/form-data">
            <input type="file" name="file" />
            <input type="submit" value="Submit">
        </form>
    </body>
    </html>
  • 相关阅读:
    IServiceBehavior, IOperationBehavior,IParameterInspector
    System.IO.Pipelines——高性能IO(三)
    System.IO.Pipelines——高性能IO(二)
    System.IO.Pipelines——高性能IO(一)
    背包问题 —— 四种解法解题
    波音,自动驾驶bug未修复,致346人丧生!5个月内两次坠毁!其中,包括8名中国公民
    2018年Java生态行业报告
    为什么大公司一定要使用DevOps?
    设计微服务的最佳实践
    Spring Boot面试题
  • 原文地址:https://www.cnblogs.com/zhanzhuang/p/12894880.html
Copyright © 2011-2022 走看看