File Upload & Storage
Orders often need uploads: invoices, return photos, or avatar images for the customer profile.
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
- Set
spring.servlet.multipartmax sizes in YAML. - Add
POST /api/orders/{id}/attachmentsaccepting@RequestPart. - Validate owner from the JWT subject before upload.
- Put object to storage; save metadata; return a DTO with a signed URL.
Informative example
Orders attachment upload with size/type checks.
@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);}}@Servicepublic 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;@Transactionalpublic 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.ymlspring:servlet:multipart:max-file-size: 5MBmax-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-Typealone 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.
1BeginnerQuestionWhy not store uploaded files in the database?+
Answer
2IntermediateQuestionWhere should multipart size limits live?+
Answer
spring.servlet.multipart so oversized bodies never reach business logic.3IntermediateQuestionHow do you prevent insecure direct object references on downloads?+
Answer
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.