Start learning free

LESSON 116 OF 173 · BACKEND: PAYMENTS AND OTHER SERVICES

Upload a Photo in Java

Practice

A photo is not text but bytes: numbers from 0 to 255 that only an image viewer makes sense of. A browser doesn't send a file as JSON but as multipart/form-data: the body is cut into parts, one per form field, and a file's part carries its file name and its bytes.

Spring hands you an uploaded file as a MultipartFile: a method parameter @RequestParam MultipartFile avatar gets the part named avatar. A file has getOriginalFilename(), the name it had on the sender's computer, and getBytes() gives its bytes as a byte[]. For example, a route that takes a customer's avatar:

@PostMapping("/customers/{customerId}/avatar")
Object uploadAvatar(@PathVariable int customerId, @RequestParam MultipartFile avatar) {
    return ResponseEntity.status(201).body(Map.of("name", avatar.getOriginalFilename()));
}

When the request has no such part, Spring answers 400 Bad Request by itself. To keep the bytes, a table needs a BLOB column ("binary large object"). With product_id as the primary key, each product has one photo, and INSERT OR REPLACE lets a new photo take the old one's place instead of failing.

The tests send files in the field photo (each character of these files is one byte) and look in the table with GET /check/photos:

POST /products/1/photo  (photo: mug.png, "a photo of a mug")  →  201  {"filename": "mug.png", "product_id": 1, "size": 16}
POST /products/3/photo  (photo: lamp.jpg, "a photo of a lamp")  →  201  {"filename": "lamp.jpg", "product_id": 3, "size": 17}
POST /products/1/photo  (photo: mug-new.png, "a better photo of the mug")  →  201  {"filename": "mug-new.png", "product_id": 1, "size": 25}
POST /products/1/photo  (form name=Mug, no file)  →  400  (an HTML error page)
GET /check/photos  →  200  [{"filename": "mug-new.png", "product_id": 1, "size": 25}, {"filename": "lamp.jpg", "product_id": 3, "size": 17}]

Your task: create a photos table in the constructor, then add POST /products/{productId}/photo: take the file from the field photo, store its name and bytes for the product (a new photo replaces the old one), and answer 201 with the product id, the file name and the size in bytes.


Assignment
Follow the Coding Tutorial to create the photos table and the upload method.


Hint
Answer the size, data.length, not the bytes themselves: the client already has them. db.update saves the row at once, so there is no commit to write.


STEP 1 OF 6
    Ctrl + Enter to check

    Files Upload in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free