API: Upload & download media files
Last updated
Last updated
Usually, products that you can buy are represented by at least one image. Depending on the type of product, such as audio NFT, other files can be components of the purchase:
the audio file itself
a video
PDF files with further descriptions or as a manual
Some of these files, such as thumbnails, should be stored with public access so that anyone can access them, including unauthenticated users and even search engines.
The target bucket must have already been created.
First we create a pre-signed URL, which will be the target of the actual File upload using a <form>
-Tag in HTML or a PUT-request.
Request:
POST https://media.[stage].tokenforge.tech/prepare/{{bucketName}}/my-fancy-picture.jpg
Response:
The most important attribute here is the content of the url
property. This URL contains the pre-signed URL which will be valid for a certain amount of time (depending on your default settings, e.g. 900 seconds)
By default, this File will inherit the permissions of the underlying bucket, e.g. “private”.
If we want to change the ACL to make it publicly available for read, which means public-read
, we have to put a Body into the API request like this:
Otherwise, if the underlying bucket has a different ACL and we want to upload a file as “private”, we have to set the corresponding ACL instead.
To download the file or use it, for example as the src
-attribute in an <img>
-Tag of a website, we need to create a pre-signed URL that makes the file publicly available for a specified time:
This happens with a POST-request to the MediaService:
POST
https://media.[stage].tokenforge.tech/sign/{{bucketName}}/{{imageUploadFileName}}?seconds=60
For security-reasons, we have to pass a HTTP-Header called X-TF-Signature
along with the request, which ensures that only you will have the permissions to create such pre-signed URL.
The value of this parameter can be calculated as a HMAC from the following data:
The secret will be delivered once at the time of your initial signup as client of TokenForge API.
Example-Code:
*const* data = bucketName + imageFileName
*const* signature = CryptoJS.HmacSHA256(data, secret).toString(CryptoJS.digest)
request.headers.add('X-Signature', signature)
Also, an optional query parameter is available that specifies the number of seconds this URL should be valid until it expires: ?seconds=60
Creation of Thumbnails or even other image sizes is dead easy thanks to TokenForge MediaService:
Just build an URL that points to the original file:
https://media.stage.tokenforge.tech/my-bucket/flowers.png
and add a “Size-Tag” between the bucket and the actual filename:
https://media.stage.tokenforge.tech/my-bucket/**s-thumb/**flowers.png
Even other Sizes are available depending on your own requirements:
https://media.stage.tokenforge.tech/my-bucket/**s-small**/flowers.png
https://media.stage.tokenforge.tech/my-bucket/**s-big**/flowers.png