java 159 lines · 2 tabs

File upload and download handling

David Kumar Jan 2026
2 tabs
package com.example.demo.controller;

import com.example.demo.dto.FileMetadata;
import com.example.demo.service.FileStorageService;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/files")
public class FileUploadController {

    private final FileStorageService fileStorageService;

    public FileUploadController(FileStorageService fileStorageService) {
        this.fileStorageService = fileStorageService;
    }

    @PostMapping("/upload")
    public ResponseEntity<FileMetadata> uploadFile(
        @RequestParam("file") MultipartFile file
    ) {
        FileMetadata metadata = fileStorageService.storeFile(file);
        return ResponseEntity.ok(metadata);
    }

    @PostMapping("/upload-multiple")
    public ResponseEntity<List<FileMetadata>> uploadMultipleFiles(
        @RequestParam("files") List<MultipartFile> files
    ) {
        List<FileMetadata> metadataList = files.stream()
            .map(fileStorageService::storeFile)
            .toList();
        return ResponseEntity.ok(metadataList);
    }

    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(
        @PathVariable String fileName,
        HttpServletRequest request
    ) throws IOException {
        Resource resource = fileStorageService.loadFileAsResource(fileName);

        String contentType = request.getServletContext()
            .getMimeType(resource.getFile().getAbsolutePath());
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType(contentType))
            .header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + resource.getFilename() + "\"")
            .body(resource);
    }

    @DeleteMapping("/{fileName:.+}")
    public ResponseEntity<Void> deleteFile(@PathVariable String fileName) {
        fileStorageService.deleteFile(fileName);
        return ResponseEntity.noContent().build();
    }
}
2 files · java Explain with highlit

Spring Boot handles multipart file uploads efficiently. MultipartFile represents uploaded files. I validate file types, sizes, and content. Files are stored locally, in cloud storage (S3, Azure Blob), or databases. Streaming large files prevents memory issues. Content-Disposition headers enable downloads with custom filenames. MIME types ensure proper browser handling. Virus scanning protects against malware. Asynchronous processing handles large uploads. Temporary file cleanup prevents disk space issues. Configuration limits max file size and request size. File metadata—original name, content type, size—is persisted. Proper error handling covers upload failures, storage issues, and validation errors. Security considerations include path traversal prevention and access control.


Related snips

graphql
type User {
    id: ID!
    name: String!
    email: String!
    posts: [Post!]!
    createdAt: String!

GraphQL API with Spring Boot

java graphql spring-boot
by David Kumar 3 tabs
java
package com.example.starter.config;

import com.example.starter.properties.CustomProperties;
import com.example.starter.service.CustomService;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;

Custom Spring Boot starters

java spring-boot starter
by David Kumar 4 tabs
ruby
# Installation
# rails active_storage:install
# rails db:migrate

# config/storage.yml
local:

ActiveStorage for file uploads and attachments

ruby rails active-storage
by Sarah Mitchell 2 tabs
java
package com.example.demo.config;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;

Messaging with Apache Kafka

java kafka messaging
by David Kumar 3 tabs
yaml
# Headless Service for stable DNS
apiVersion: v1
kind: Service
metadata:
  name: postgres
  namespace: production

Kubernetes StatefulSets for stateful workloads

kubernetes k8s statefulsets
by Ryan Nakamura 1 tab
sql
CREATE TABLE users (
    id BIGSERIAL PRIMARY KEY,
    username VARCHAR(100) NOT NULL UNIQUE,
    email VARCHAR(255) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

Database migration with Flyway

java flyway database-migration
by David Kumar 6 tabs

Share this code

Here's the card — post it anywhere.

File upload and download handling — share card
Link copied