#1
If you're storing document files like PDFs, Word documents, or text files in MinIO, chances are you’ll need to read or preview those files directly from your Spring Boot application. Whether it's for rendering content on a web page or analyzing file contents, it's important to know how to read files without forcing users to download them.
In this guide, you'll learn how to read document files stored in MinIO using Spring Boot, and stream or access their contents in a way that's friendly for preview or processing—not downloading.

What You’ll Learn

  • How to connect Spring Boot to MinIO
  • How to access and read document files like .pdf, .docx, and .txt
  • How to return file contents or stream them as responses
  • How to avoid download prompts while reading content
Note: This tutorial assumes MinIO is already running and connected to your Spring Boot app. If not, check guides like Connect Spring Boot to MinIO Server or MinIO Dependency Setup in Spring Boot.

Step 1: Add the MinIO Java SDK

To interact with MinIO, you’ll need to include the official MinIO Java client in your pom.xml:
<dependency>
  <groupId>io.minio</groupId>
  <artifactId>minio</artifactId>
  <version>8.5.3</version> <!-- Use latest available -->
</dependency>

Step 2: Set Up MinIO Configuration in application.properties

Here’s a sample configuration to place in your application.properties:
minio.url=http://localhost:9000
minio.accessKey=minioadmin
minio.secretKey=minioadmin
minio.bucketName=documents

Step 3: Create MinIO Client Configuration

Create a config class to create and inject the MinioClient bean:
@Configuration
public class MinioConfig {

    @Value("${minio.url}")
    private String url;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

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

Step 4: Create a Service to Read Files from MinIO

This service reads document files directly from the MinIO bucket as a stream.
@Service
public class DocumentReadService {

    @Value("${minio.bucketName}")
    private String bucketName;

    private final MinioClient minioClient;

    public DocumentReadService(MinioClient minioClient) {
        this.minioClient = minioClient;
    }

    public InputStream readDocument(String fileName) throws Exception {
        return minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .build());
    }
}
This returns the InputStream of the file—you can process or preview it depending on its type.

Step 5: Create a Controller to Serve File Content

Now let’s create an endpoint to stream the content directly—without triggering a download:
@RestController
@RequestMapping("/api/documents")
public class DocumentPreviewController {

    private final DocumentReadService documentReadService;

    public DocumentPreviewController(DocumentReadService documentReadService) {
        this.documentReadService = documentReadService;
    }

    @GetMapping("/preview/{fileName}")
    public ResponseEntity<InputStreamResource> previewDocument(@PathVariable String fileName) {
        try {
            InputStream inputStream = documentReadService.readDocument(fileName);

            // Infer content type by file extension
            String contentType = inferContentType(fileName);

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(new InputStreamResource(inputStream));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(null);
        }
    }

    private String inferContentType(String fileName) {
        if (fileName.endsWith(".pdf")) {
            return "application/pdf";
        } else if (fileName.endsWith(".txt")) {
            return "text/plain";
        } else if (fileName.endsWith(".docx")) {
            return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        }
        return "application/octet-stream";
    }
}
This returns the file contents in the browser (if previewable) rather than triggering a download.

How It Works

When a user accesses /api/documents/preview/sample.pdf, the app:
  • Fetches the PDF file as a stream from MinIO
  • Infers the content type based on file extension
  • Returns the stream using InputStreamResource
  • Allows the browser to display the document inline (if supported)

Testing the Preview Endpoint

Use Postman or your browser to test this endpoint:
GET http://localhost:8080/api/documents/preview/sample.pdf
If the file exists and is a valid PDF, it should open right in your browser window. This behavior also works for text files and may work for .docx depending on your browser setup.

Best Practices

  • Always check file type to prevent serving unwanted content
  • Handle missing or invalid file names gracefully
  • Cache file type detection for better performance
  • Avoid exposing raw file paths or user-uploaded names directly
  • Use headers like Content-Disposition: inline if needed for specific browsers

image quote pre code