Upload Image
We are using the Backblaze B2 bucket to store all the media of the website. Our bucket name is urbanfits. It's exposed through the S3 compatible API, so please refer to the AWS S3 documentation as well for the context.
There are different ways to upload the images on the bucket but here we're using the most suitable way which involves 2 steps:
- First we'll get a presigned url from the bucket which will be signed for a limited time for securely upload the image.
- Secondly we will upload the actual image by sending it to that Presigned URL, using it as an API.
- Get Presigned URL
- Upload image file on Presigned URL
1. Get Presigned URL
Endpoint
GET /S3/signed-url
Payload
file_key and an optional one named content_type. You need to enter the relative path within the bucket file system where you want to host the respected file. For example the path for uploading the user profile pictures is specific and should be strictly followed i.e
user-profiles/[user_id]. In this previous mentioned path, the user id should suffixed e.g the user id is
651ab014f10bff23784dd8e8 then the path will look like this: user-profiles/651ab014f10bff23784dd8e8. And finally the API URL will be like this: /S3/signed-url?file_key=user-profiles/651ab014f10bff23784dd8e8So in this case we have requested a presigned url from the bucket which will automatically host the file on the specified path for which we requested it.
The
content_type query defaults to image/webp. It is signed into the url, which means the upload request in the next step must send the exact same Content-Type header, otherwise the bucket rejects the signature.Response
1
2
3
4
{
"success": true,
"uploadUrl": "https://urbanfits.s3.eu-central-003.backblazeb2.com/user-profiles/651ab014f10bff23784dd8e8?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=**********%2F20240625%2Feu-central-003%2Fs3%2Faws4_request&X-Amz-Date=20240625T220903Z&X-Amz-Expires=900&X-Amz-Signature=735f613109b33c6f1fc16c7b8ae3062c318fdab683a39facf22aa0bc9d3e0930&X-Amz-SignedHeaders=content-type%3Bhost&x-id=PutObject"
}2. Upload image on Presigned URL
Endpoint
PUT https://urbanfits.s3.eu-central-003.backblazeb2.com/user-profiles/651ab014f10bff23784dd8e8...
Payload
Now in the body of request, simply put the file as payload along with the Content-Type header matching the one the url was signed for, and upload the file. The API will return the confirmation of file being successfully uploaded. And after the confirmation, you can just update the file url wherever you need to update in our server as you know the file url was what we have already requested the presigned url for which in this case will be user-profiles/651ab014f10bff23784dd8e8 .
And for using the image in application, you can prepend the base image url to our actual file url just as mentioned in the API Prerequisites : Images Usage