Springboot integrates Minio to implement file upload and download

Table of contents

 

1. Minion

1.1 Minio download

2. Springboot and Minio implement file storage


 

1. Minion

Minio is a flexible, high-performance, open source object storage solution suitable for a variety of storage needs and can be integrated with cloud computing, containerization, big data and applications. It provides users with autonomous control and scalability, making it a powerful storage solution.

1.1 Minio download

To install the MinIO server, download the MinIO executable from the following URL:

https://dl.min.io/server/minio/release/windows-amd64/minio.exe

Use this command to launch the local MinIO instance in the download folder.

.\minio.exe server C:\minio --console-address :9090

Print its output to the system console, similar to the following:

API: http://192.0.2.10:9000  http://127.0.0.1:9000
RootUser: minioadmin
RootPass: minioadmin

Console: http://192.0.2.10:9090 http://127.0.0.1:9090
RootUser: minioadmin
RootPass: minioadmin

Command-line: https://min.io/docs/minio/linux/reference/minio-mc.html
   $ mc alias set myminio http://192.0.2.10:9000 minioadmin minioadmin

Documentation: https://min.io/docs/minio/linux/index.html

WARNING: Detected default credentials 'minioadmin:minioadmin', we recommend that you change these values with 'MINIO_ROOT_USER' and 'MINIO_ROOT_PASSWORD' environment variables.

The process is bound to the current PowerShell or Command Prompt window. Closing the window will stop the server and end the process.

2. Springboot and Minio implement file storage

Inpom.xml file, add MinIO dependencies:

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

Inapplication.properties file, configure the MinIO connection information:

minio:
  endpoint: http://127.0.0.1:9000
  accessKey: admin1234
  secretKey: admin1234
  bucketName: bucket1

In the Spring Boot configuration class, create a MinIO client instance:

@Data
@Configuration
public class MinioConfig {

    /**
     * 访问地址
     */
    @Value("${minio.endpoint}")
    private String endpoint;

    /**
     * accessKey类似于用户ID,用于唯一标识你的账户
     */
    @Value("${minio.accessKey}")
    private String accessKey;

    /**
     * secretKey是你账户的密码
     */
    @Value("${minio.secretKey}")
    private String secretKey;

    /**
     * 默认存储桶
     */
    @Value("${minio.bucketName}")
    private String bucketName;

    @Bean
    public MinioClient minioClient() {
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
        return minioClient;
    }
}

Upload and download files:

@Slf4j
@RestController
@RequestMapping("/oss")
public class OSSController {



    @Autowired
    private MinioConfig minioProperties;

    @Autowired
    private MinioClient minioClient;

    /**
     * 文件上传
     *
     * @param file
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if (file == null || file.getSize() == 0) {
            log.error("==> 上传文件异常:文件大小为空 ...");
            throw new RuntimeException("文件大小不能为空");
        }
        boolean b = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        if(!b){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
        }
        String originalFileName = file.getOriginalFilename();
        String contentType = file.getContentType();

        String key = UUID.randomUUID().toString().replace("-", "");
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));

        String objectName = String.format("%s%s", key, suffix);

        log.info("==> 开始上传文件至 Minio, ObjectName: {}", objectName);
        InputStream inputStream = file.getInputStream();
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(objectName)
                .stream(inputStream, file.getSize(), -1)
                .contentType(contentType)
                .build());

        String url = String.format("%s/%s/%s", minioProperties.getEndpoint(), minioProperties.getBucketName(), objectName);
        log.info("==> 上传文件至 Minio 成功,访问路径: {}", url);
        inputStream.close();
        return url;
    }

    @GetMapping("/download")
    public void download(@RequestParam("filename") String filename, HttpServletResponse response) {
        try(InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(filename)
                .build())) {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.close();
        } catch (Exception e) {
            log.error("file download from minio exception, file name: {}", filename,  e);
        }
    }

}

Note: Set the bucket permissions Access Policy to public, otherwise you will not be able to access the images.

70d6ac713905480d977ad965d7fc0270.png

 

Guess you like

Origin blog.csdn.net/qq_43649937/article/details/134157965