Multipart Requests
November 15, 2020
Background
The HTTP header Content-Type
describes the kind of data being sent in the request. It can be set to things like text/plain
and application/json
when you need to send either of those formats respectively. However, when you need to send multiple types of data in the same HTTP request, you use a multipart type for the content header.
Multipart requests are commonly used for
- Uploading a file to a server (the file and its metadata are different types)
- Sending an email (email text and attachments)
Use Case: File Upload To Server
Option 1: Base64 Encode/Decode
One option for sending a file to a server is to base64 encode the file contents as a string and send it in the body of a POST request. The server would then need to base64 decode the string and then can do anything it needs (ex: save it as a file locally).
{"fileString": "<base64EncodedString here>","name": "index.html"}
The overhead of encoding and decoding means this method will take slightly more CPU power, and increase the size of the file a bit (encoding).
Option 2: Multipart File Upload
The other option (which will be shown below) is to use multipart form-data to do the upload.
Postman
Uploading files via postman looks like so. This is a POST request using form-data
, with the key as file
and value as the file to upload.
Frontend (Fetch) and Backend (Spring)
The frontend can use any http client to send the file to ther server. A basic example that uses the native fetch
javascript client looks like so. This creates a FormData object and passes the file. The file parameter passed here will be of type File
.
//Send a filefunction sendFile (file) {const formData = new FormData()formData.append('file', file)fetch('http://localhost:8081/saveFile', {method: 'POST',body: formData}).then(response => response.json())}
Backend spring code looks like so. It reads in the file as a MultipartFile
. You can check all the available properties on that class to see what can be extracted.
@PostMapping("/saveFile")@ResponseStatus(HttpStatus.OK)public String saveFile(@RequestParam("file") MultipartFile file){//Get file nameString filename = file.getOriginalFilename();System.out.println("Recieved file :" + filename);//Do other things like save file to disk....return "{}";}