Right now the shop stores any file of any size. Someone uploads page.html, a web page with a script in it, and getPhoto serves it as text/html from your shop's own address: the browser runs the script as if your shop had written it. Someone else uploads a huge video, and the database fills up. So an upload checks rules before it stores anything.
A rule can be a list of allowed values, kept in a constant at the top of the class: !LIST.contains(value) refuses everything else. For example, on another value:
static final List<String> CURRENCIES = Arrays.asList("USD", "EUR");
@GetMapping("/prices")
Object getPrices(@RequestParam(required = false) String currency) {
if (!CURRENCIES.contains(currency)) {
return ResponseEntity.status(400).body(Map.of("error", "Unknown currency"));
}
...
}
Find a file's type from its name with URLConnection.guessContentTypeFromName, the same way getPhoto does when it serves it; a name with no extension gives null, and a list made with Arrays.asList simply answers false when asked whether it contains null. Two statuses say what's wrong: 415 Unsupported Media Type ("I don't take this kind of file") and 413 Content Too Large. Exactly 1000 bytes is still fine.
POST /products/1/photo (photo: mug.png, 16 bytes) → 201 {"filename": "mug.png", "product_id": 1, "size": 16}
POST /products/1/photo (photo: page.html) → 415 {"error": "Only PNG and JPEG photos"}
POST /products/1/photo (photo: mug, no extension) → 415 {"error": "Only PNG and JPEG photos"}
POST /products/3/photo (photo: lamp.jpg, 1001 bytes) → 413 {"error": "The photo is larger than 1000 bytes"}
POST /products/3/photo (photo: lamp.jpg, 1000 bytes) → 201 {"filename": "lamp.jpg", "product_id": 3, "size": 1000}
POST /products/5/photo (photo: Plant.JPG, 18 bytes) → 201 {"filename": "Plant.JPG", "product_id": 5, "size": 18}
GET /products/1/photo → 200 (image/png, 16 bytes)
Your task: add the constants PHOTO_TYPES ("image/png" and "image/jpeg") and MAX_PHOTO_BYTES (1000), then make uploadPhoto answer 415 for any other type and 413 for a file over 1000 bytes, before it stores anything.
Assignment
Follow the Coding Tutorial to add the two upload rules.
Hint
Check the type at the top of uploadPhoto, and the size right after reading its bytes. Use > for the size, not >=: a file of exactly 1000 bytes is allowed. Make PHOTO_TYPES with Arrays.asList: a List.of list throws when asked about null.
Free plan: 30 tutor messages. PRO is unlimited.
