Contoh Penggunaan Minio pada Java API Spring Boot

Pada postingan kali ini kami akan share terkait conoh sederhana peggunaan Minio pada Java API dengan framework Spring Boot. Langsung saja simak step2 nya.

Tambahkan depedency pada pom.xml

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

Tambahkan code pada application.properties

# Minio Host
spring.minio.url=https://play.min.io
# Minio Bucket name for your application
spring.minio.bucket=asiatrip
# Minio access key (login)
spring.minio.access-key=Q3AM3UQ867SPQQA43P2F
# Minio secret key (password)
spring.minio.secret-key=zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG

spring.servlet.multipart.enabled=true
# Threshold after which files are written to disk.
spring.servlet.multipart.file-size-threshold=2KB
# Max file size.
spring.servlet.multipart.max-file-size=5MB
# Max Request Size
spring.servlet.multipart.max-request-size=10MB

Selanjutnnya silahkan buat controller dan masukkan code dibawah ini


package com.lkpp.controllers;

import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/minio")
public class MinioController {

    @Value("${spring.minio.url}")
    public String minioUrl;

    @Value("${spring.minio.bucket}")
    public String minioBucket;

    @Value("${spring.minio.access-key}")
    public String minioAccessKey;

    @Value("${spring.minio.secret-key}")
    public String minioSecretKey;

    @PostMapping("/upload")
    public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioUrl)
                    .credentials(minioAccessKey, minioSecretKey)
                    .build();

            // Simpan file di bucket MinIO
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioBucket)
                            .object(file.getOriginalFilename())
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            return ResponseEntity.status(HttpStatus.OK).body("File uploaded successfully!");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file.");
        }
    }

    @GetMapping("/download/{filename}")
    public ResponseEntity downloadFile(@PathVariable String filename) {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioUrl)
                    .credentials(minioAccessKey, minioSecretKey)
                    .build();

            // Dapatkan input stream dari objek
            InputStream inputStream = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(minioBucket)
                            .object(filename)
                            .build());

            return ResponseEntity.ok()
                    .body(new InputStreamResource(inputStream));
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @GetMapping("/list")
    public ResponseEntity> listFiles() {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioUrl)
                    .credentials(minioAccessKey, minioSecretKey)
                    .build();

            List fileList = new ArrayList<>();
            Iterable> results = minioClient.listObjects(
                    ListObjectsArgs.builder()
                            .bucket(minioBucket)
                            .build());

            for (Result result : results) {
                Item item = result.get();
                fileList.add(item.objectName());
            }

            return ResponseEntity.ok().body(fileList);
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @GetMapping("/images/{filename:.+}")
    public void getImage(@PathVariable String filename, HttpServletResponse response) {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioUrl)
                    .credentials(minioAccessKey, minioSecretKey)
                    .build();

            // Dapatkan input stream dari objek
            InputStream inputStream = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(minioBucket)
                            .object(filename)
                            .build());

            // Set content type sesuai dengan jenis file
            String contentType = "image/jpg"; // Ganti sesuai dengan jenis file yang sesuai
            response.setContentType(contentType);

            // Salin input stream ke output stream response
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, bytesRead);
            }

            response.getOutputStream().flush();
        } catch (MinioException | IOException | InvalidKeyException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }
}

Selanjutya silahkan testing menggunakan postman atau pakai swagger.



Untuk selanjutnya bisa dikembangkan sendiri dan bisa pelajari via doc nya.

https://min.io/docs/minio/kubernetes/upstream/




Post a Comment

0 Comments