The Right Way To UPLOAD A File Using REST

Possible options

Basically there are 3 options that we can do

1. Base64 encoding the file and then send the file as path of the body

In here you can either use request body or form-data which will send the request to the server.

For Content-type you can specify which content-type you wanna use. In the case it's an image, you should be able to use image/jpeg or image/png

Otherwise you can just do Mutli-part content-type.

Note: This will increase the file size by around 33%, which is not good for big file size.

2. Upload the metadata first and then upload the file

This is the recommended way since the metadata is normally faster to create and hence can be processed first.

The actual upload job can be done after the metadata upload job is complete.

For example

POST http://localhost.com/upload
{
	"name": "some_file_name",
	"size": "file_size",
	"type": "file_type"
	"Content-type: "x-www-form-urlencoded"
}

Server will return 201 CREATED will the URL that client will use to upload this file

201 
{
	"name": "some_file_name",
	"id": "123456"
	"uploadUrl": "http://localhost.com/upload/123456"
}

Then the client can use this uploadUrl to upload the file:

POST http://localhost.com/upload/123456
{
	"name": "some_file_name"
	"file": "@file"
	"Content-type": "multipart/form-data"
}

The nice thing about this:

  • We can give the client the correct link of the server that the file needed to be uploaded to.
    • To handle different media type
    • To offload an upload server in the case that it's weighted down.
      • Ofcourse this can be done using load balancer as well
  • To process the metadata job first which is very quick to do
    • With meta-data job processed, we can do a Resumable Upload in the case the client experienced some issue uploading the file, the client can then continue where it left off

3. Upload the goal and metadata the same time

Similar to above but we choose to upload both goal and metadata in the same time, the server will then return the status of the uploaded metadata as the status of the whole job while processing the job in the background.