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

    File Upload & Storage

    Uploads are easy to do wrong.

    Course progress0%
    Focus
    3 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Uploads are easy to do wrong. The right pattern: stream to S3 (or compatible), store only metadata in your DB, return a signed URL for downloads.

    Informative example

    ts
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AvatarDto upload(@RequestPart("file") MultipartFile file, @AuthenticationPrincipal UserPrincipal me) {
    if (file.getSize() > 5 * 1024 * 1024) throw new PayloadTooLargeException();
    if (!ALLOWED_TYPES.contains(file.getContentType())) throw new UnsupportedMediaTypeException();
    String key = "avatars/" + me.id() + "/" + UUID.randomUUID();
    s3.putObject(b -> b.bucket("acme").key(key).contentType(file.getContentType()),
    RequestBody.fromInputStream(file.getInputStream(), file.getSize()));
    avatarRepo.save(new Avatar(me.id(), key));
    return new AvatarDto(signedUrl(key));
    }
    # application.yml
    spring:
    servlet:
    multipart:
    max-file-size: 10MB
    max-request-size: 10MB

    Best practices

    • Cap upload size at the framework and the gateway.
    • Validate MIME and magic bytes — clients lie.
    • Store binaries in object storage (S3/GCS), not in the DB.
    Ready to mark this lesson complete?Track your journey across the entire course.