Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 52

    File Upload & Storage

    Orders often need uploads: invoices, return photos, or avatar images for the customer profile.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Orders often need uploads: invoices, return photos, or avatar images for the customer profile. Doing it wrong means OOM from huge multipart bodies or binaries stuffed into Postgres.

    The Boot 3 pattern: accept MultipartFile (or stream), validate size and content type, write bytes to object storage (S3-compatible), and persist only metadata (key, content type, owner) in the database.

    Downloads should use time-limited signed URLs — the API never proxies multi-megabyte files on the request thread if avoidable.

    This lesson hardens TechLearningPRO Orders uploads with servlet multipart limits and safe storage boundaries.

    Purpose of this lesson

    Implement safe multipart upload for Orders: validate, store in object storage, keep metadata in the DB.

    Understanding the topic

    Files leave the JVM; the database remembers pointers.

    • multipart limits: framework + gateway caps.
    • validation: size, MIME, and preferably magic bytes.
    • object storage: S3/GCS/MinIO for blobs.
    • metadata: orderId, key, contentType, checksum in Postgres.
    • access: signed URLs or authenticated download tickets.

    Step-by-step explanation

    1. Set spring.servlet.multipart max sizes in YAML.
    2. Add POST /api/orders/{id}/attachments accepting @RequestPart.
    3. Validate owner from the JWT subject before upload.
    4. Put object to storage; save metadata; return a DTO with a signed URL.

    Informative example

    Orders attachment upload with size/type checks.

    java
    @RestController
    @RequestMapping("/api/orders")
    public class OrderAttachmentController {
    private final OrderAttachmentService attachments;
    public OrderAttachmentController(OrderAttachmentService attachments) {
    this.attachments = attachments;
    }
    @PostMapping(path = "/{orderId}/attachments", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    AttachmentView upload(
    @PathVariable long orderId,
    @AuthenticationPrincipal Jwt jwt,
    @RequestPart("file") MultipartFile file) {
    return attachments.store(jwt.getSubject(), orderId, file);
    }
    }
    @Service
    public class OrderAttachmentService {
    private static final Set<String> ALLOWED = Set.of("image/jpeg", "image/png", "application/pdf");
    private final ObjectStorage storage;
    private final OrderRepository orders;
    private final AttachmentRepository attachments;
    @Transactional
    public AttachmentView store(String customerId, long orderId, MultipartFile file) {
    orders.findOwned(orderId, customerId).orElseThrow(() -> new OrderNotFoundException(orderId));
    if (file.getSize() > 5 * 1024 * 1024) throw new PayloadTooLargeException();
    if (!ALLOWED.contains(file.getContentType())) throw new UnsupportedMediaTypeException();
    String key = "orders/%d/%s".formatted(orderId, UUID.randomUUID());
    storage.put(key, file);
    AttachmentEntity saved = attachments.save(AttachmentEntity.of(orderId, key, file.getContentType()));
    return AttachmentView.from(saved, storage.signedGetUrl(key));
    }
    }
    # application.yml
    spring:
    servlet:
    multipart:
    max-file-size: 5MB
    max-request-size: 6MB

    Real-world use

    Support agents uploaded 80MB phone videos into Orders and blew heap on a small pod. Caps at the gateway and servlet multipart layer, plus S3 storage, kept the JVM stable and left only keys in Postgres.

    Security implications

    Uploads are a classic malware and IDOR vector.

    • Always authorize against the authenticated order owner.
    • Do not reflect raw filenames into headers without sanitizing.
    • Keep cloud credentials in ${OBJECT_STORAGE_ACCESS_KEY} placeholders.

    Best practices

    • Cap size at gateway and Boot; validate type; scan when policy requires.
    • Store blobs in object storage; DB holds metadata only.
    • Signed URLs with short TTL for downloads.

    Common mistakes

    • Trusting Content-Type alone without size caps.
    • Saving files under a public directory inside the container image.
    • Serving attachments without checking order ownership.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhy not store uploaded files in the database?+

    Answer

    Blobs bloat backups, hurt performance, and couple binary I/O to OLTP; object storage scales independently while the DB stores keys.
    2IntermediateQuestionWhere should multipart size limits live?+

    Answer

    At both the API gateway and spring.servlet.multipart so oversized bodies never reach business logic.
    3IntermediateQuestionHow do you prevent insecure direct object references on downloads?+

    Answer

    Check the authenticated principal owns the order before issuing a signed URL or streaming the object.

    Hands-on exercise

    Lab. Implement attachment upload with a 1MB cap and allow-list of PNG/JPEG. Reject oversized files and uploads for orders the JWT subject does not own. Persist metadata only.

    Summary

    File upload for TechLearningPRO Orders is validate-store-metadata: Boot multipart limits, object storage, and ownership checks keep binaries out of the database.

    Ready to mark this lesson complete?Track your journey across the entire course.