Handling Large File Uploads in Spring Boot Applications

Handling large file uploads efficiently is crucial for modern web applications. Spring Boot provides robust support for file uploads using MultipartFile. This guide explains how to configure and handle large file uploads step by step.

1. Add Required Dependencies

Ensure your pom.xml includes the necessary dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

For Gradle users, add:

implementation 'org.springframework.boot:spring-boot-starter-web'

2. Configure File Upload Limits

Spring Boot allows configuring file size limits in application.properties:

spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=200MB

Alternatively, use application.yml:

spring:
  servlet:
    multipart:
      enabled: true
      max-file-size: 100MB
      max-request-size: 200MB

3. Create a REST Controller for File Upload

Define an endpoint to handle file uploads using MultipartFile:

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import java.io.*;
import java.nio.file.*;

@RestController
@RequestMapping("/upload")
public class FileUploadController {
    private static final String UPLOAD_DIR = "uploads/";

    @PostMapping("/file")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            Path filePath = Paths.get(UPLOAD_DIR + file.getOriginalFilename());
            Files.createDirectories(filePath.getParent());
            Files.write(filePath, file.getBytes());
            return ResponseEntity.ok("File uploaded successfully: " + file.getOriginalFilename());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file");
        }
    }
}

4. Handling Large File Uploads Efficiently

4.1 Streaming Large Files

For large files, use StreamingResponseBody to prevent memory overload:

@GetMapping("/download/{filename}")
public ResponseEntity<StreamingResponseBody> downloadFile(@PathVariable String filename) {
    File file = new File(UPLOAD_DIR + filename);
    if (!file.exists()) {
        return ResponseEntity.notFound().build();
    }
    StreamingResponseBody responseBody = outputStream -> {
        try (InputStream inputStream = new FileInputStream(file)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    };
    return ResponseEntity.ok(responseBody);
}

4.2 Store Files in a Cloud Storage (Optional)

To store large files in cloud storage like Amazon S3, use AWS SDK:

<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>s3</artifactId>
    <version>2.17.89</version>
</dependency>

Upload files to S3:

import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;

S3Client s3 = S3Client.builder().build();
PutObjectRequest request = PutObjectRequest.builder()
    .bucket("my-bucket")
    .key(file.getOriginalFilename())
    .build();
s3.putObject(request, Paths.get(UPLOAD_DIR + file.getOriginalFilename()));

5. Implement Security Measures

5.1 Validate File Type

Restrict uploads to specific file types to prevent malicious file uploads:

if (!file.getContentType().equals("image/png") && !file.getContentType().equals("image/jpeg")) {
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid file type");
}

5.2 Limit File Size in Code

Check file size before saving:

if (file.getSize() > 100 * 1024 * 1024) {
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File too large");
}

5.3 Scan for Malware

Use ClamAV or third-party APIs to scan uploaded files for viruses.

Conclusion

Spring Boot simplifies handling large file uploads by providing built-in multipart support. By optimizing file storage, implementing security checks, and using cloud storage, you can efficiently manage large file uploads in your applications.

Related post

Leave a Reply

Your email address will not be published. Required fields are marked *