Examples
Here are some example requests and responses to understand the API usage.
Uploading file from file system
curl -X POST "https://upload.imagekit.io/api/v1/files/upload" \ -u your_private_api_key: \ -F 'file=@/Users/username/Desktop/my_file_name.jpg;type=image/jpg' \ -F 'fileName=my_file_name.jpg'
var ImageKit = require("imagekit"); var fs = require('fs'); var imagekit = new ImageKit({ publicKey : "your_public_key", privateKey : "your_private_key", urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/" }); fs.readFile('image.jpg', function(err, data) { if (err) throw err; // Fail if the file can't be read. imagekit.upload({ file : data, //required fileName : "my_file_name.jpg", //required tags: ["tag1", "tag2"] }, function(error, result) { if(error) console.log(error); else console.log(result); }); });
import base64 import os import sys from imagekitio import ImageKit imagekit = ImageKit( public_key='your_public_key', private_key='your_private_key', url_endpoint = 'your_url_endpoint' ) upload = imagekit.upload( file=open("image.jpg", "rb"), file_name="my_file_name.jpg", options=UploadFileRequestOptions( tags = ["tag1", "tag2"] ) ) print("Upload binary", upload) # Raw Response print(upload.response_metadata.raw) # print that uploaded file's ID print(upload.file_id)
use ImageKit\ImageKit; $public_key = "your_public_key"; $your_private_key = "your_private_key"; $url_end_point = "https://ik.imagekit.io/your_imagekit_id"; $sample_file_path = "/sample.jpg"; $imageKit = new ImageKit( $public_key, $your_private_key, $url_end_point ); // Upload Image - Binary $uploadFile = $imageKit->uploadFile([ "file" => fopen(__DIR__."/image.jpg", "r"), "fileName" => "my_file_name.jpg", "tags" => ["tag1", "tag2"] ]); echo ("Upload binary file : " . json_encode($uploadFile));
byte[] bytes= Files.readAllBytes(Paths.get("/path/to/file.jpg")); FileCreateRequest fileCreateRequest =new FileCreateRequest(bytes, "sample_image.jpg"); fileCreateRequest.setUseUniqueFileName(false); Result result = ImageKit.getInstance().upload(fileCreateRequest);
imagekitio = ImageKit::ImageKitClient.new("your_private_key", "your_public_key", "your_url_endpoint") file = open("sample.jpg", "rb") upload = imagekitio.upload_file(file, "my_file_name.jpg", { tags: %w[tag1 tag2] })
ik, err := ImageKit.New() const base64Image = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" resp, err := ik.Upload.Upload(ctx, base64Image, uploader.UploadParam{})
var imagekit = new ImageKit({ publicKey : "your_public_api_key", privateKey : "your_private_api_key", urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/" }); byte[] bytes = File.ReadAllBytes("/path/to/file.jpg"); FileCreateRequest ob = new FileCreateRequest { file = bytes, fileName = "file_name1.jpg" }; Result resp2 = imagekit.Upload(ob);
Uploading base64 encoded file with some tags
curl -X POST "https://upload.imagekit.io/api/v1/files/upload" \ -u your_private_api_key: \ -F 'file=iVBORw0KGgoAAAAN' \ -F 'fileName=my_file_name.jpg' \ -F 'tags=tag1,tag2'
var ImageKit = require("imagekit"); var fs = require('fs'); var imagekit = new ImageKit({ publicKey : "your_public_api_key", privateKey : "your_private_api_key", urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/" }); var base64Img = "iVBORw0KGgoAAAAN"; imagekit.upload({ file : base64Img, //required fileName : "my_file_name.jpg", //required tags: ["tag1","tag2"] }, function(error, result) { if(error) console.log(error); else console.log(result); });
import base64 import os import sys from imagekitio import ImageKit imagekit = ImageKit( public_key='your public_key', private_key='your private_key', url_endpoint = 'your url_endpoint' ) with open("image.jpg", mode="rb") as img: imgstr = base64.b64encode(img.read()) upload = imagekit.upload( file=imgstr, file_name="my_file_name.jpg", options=UploadFileRequestOptions( response_fields = ["is_private_file", "custom_metadata", "tags"], is_private_file = False, tags = ["tag1", "tag2"], webhook_url = "url", overwrite_file = False, overwrite_ai_tags = False, overwrite_tags = False, overwrite_custom_metadata = True, custom_metadata = {"test": 11}) ), ) print("Upload base64", upload) # Raw Response print(upload.response_metadata.raw) # print that uploaded file's ID print(upload.file_id) # print that uploaded file's version ID print(upload.version_info.id)
use ImageKit\ImageKit; $public_key = "your_public_key"; $your_private_key = "your_private_key"; $url_end_point = "https://ik.imagekit.io/your_imagekit_id"; $sample_file_path = "/sample.jpg"; $imageKit = new ImageKit( $public_key, $your_private_key, $url_end_point ); $img = file_get_contents(__DIR__."/image.jpg"); // Encode the image string data into base64 $base64Img = base64_encode($img); // Upload Image - base64 $uploadFile = $imageKit->uploadFile([ "file" => $base64Img, "fileName" => "my_file_name.jpg", "tags" => ["tag1", "tag2"] ]); echo ("Upload base64" . json_encode($uploadFile));
FileCreateRequest fileCreateRequest =new FileCreateRequest(base64, "sample_base64_image.jpg"); Result result = ImageKit.getInstance().upload(fileCreateRequest);
imagekitio = ImageKitIo::Client.new("your_private_key", "your_public_key", "your_url_endpoint") image64 = Base64.encode64(File.open("sample.jpg", "rb").read) upload = imagekitio.upload_file( file: image64, file_name: "my_file_name.jpg", tags: %w[tag1 tag2] )
ik, err := ImageKit.New() const base64Image = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" resp, err := ik.Upload.Upload(ctx, base64Image, uploader.UploadParam{ FileName: "my_file_name.jpg", Tags: "tag1,tag2", })
var imagekit = new ImageKit({ publicKey : "your_public_api_key", privateKey : "your_private_api_key", urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/" }); var base64ImageRepresentation = "iVBORw0KGgoAAAAN"; FileCreateRequest ob2 = new FileCreateRequest { file = base64ImageRepresentation, fileName = Guid.NewGuid().ToString(), }; List<string> tags = new List<string> { "tags1", "tags2" }; ob.tags = tags; Result resp = imagekit.Upload(ob2);
Uploading file via URL
curl -X POST "https://upload.imagekit.io/api/v1/files/upload" \ -u your_private_api_key: \ -F 'file=https://imagekit.io/image.jpg' \ -F 'fileName=my_file_name.jpg'
var ImageKit = require("imagekit"); var fs = require('fs'); var imagekit = new ImageKit({ publicKey : "your_public_api_key", privateKey : "your_private_api_key", urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/" }); imagekit.upload({ file : "https://imagekit.io/image.jpg", //required fileName : "my_file_name.jpg" //required }, function(error, result) { if(error) console.log(error); else console.log(result); });
import base64 import os import sys from imagekitio import ImageKit imagekit = ImageKit( public_key='your public_key', private_key='your private_key', url_endpoint = 'your url_endpoint' ) with open("image.jpg", mode="rb") as img: imgstr = base64.b64encode(img.read()) upload = imagekit.upload( file="https://imagekit.io/image.jpg", file_name="my_file_name.jpg", options=UploadFileRequestOptions(), ) print("Upload url", upload) # Raw Response print(upload.response_metadata.raw) # print that uploaded file's ID print(upload.file_id)
use ImageKit\ImageKit; $public_key = "your_public_key"; $your_private_key = "your_private_key"; $url_end_point = "https://ik.imagekit.io/your_imagekit_id"; $sample_file_path = "/sample.jpg"; $imageKit = new ImageKit( $public_key, $your_private_key, $url_end_point ); // Upload Image - URL $uploadFile = $imageKit->uploadFile([ "file" => "https://imagekit.io/image.jpg", "fileName" => "my_file_name.jpg" ]); echo ("Upload URL" . json_encode($uploadFile));
FileCreateRequest fileCreateRequest = new FileCreateRequest("image_url", "my_file_name.jpg"); Result result = ImageKit.getInstance().upload(fileCreateRequest);
imagekitio = ImageKit::ImageKitClient.new("your_private_key", "your_public_key", "your_url_endpoint") upload = imagekitio.upload_file( file: "image_url", file_name: "my_file_name.jpg" )
url := "https://imagekit.io/image.jpg" resp, err := ik.Upload.Upload(ctx, url, uploader.UploadParam{ FileName: "my_file_name.jpg", })
var imagekit = new ImageKit({ publicKey : "your_public_api_key", privateKey : "your_private_api_key", urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/" }); FileCreateRequest request = new FileCreateRequest { file = "image_url", fileName = "file_name.jpg" }; Result resp1 = imagekit.Upload(request);
Setting custom metadata during upload
curl -X POST "https://upload.imagekit.io/api/v1/files/upload" \ -u your_private_api_key: \ -F 'file=https://ik.imagekit.io/ikmedia/red_dress_woman.jpeg' \ -F 'fileName=women_in_red.jpg' \ -F 'customMetadata={"brand":"Nike", "color":"red"}'
var ImageKit = require("imagekit"); var fs = require('fs'); var imagekit = new ImageKit({ publicKey : "your_public_api_key", privateKey : "your_private_api_key", urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/" }); imagekit.upload({ file : "https://ik.imagekit.io/ikmedia/red_dress_woman.jpeg", fileName : "women_in_red.jpg", customMetadata : { "brand": "Nike", "color": "red" } }, function(error, result) { if(error) console.log(error); else console.log(result); });
import base64 import os import sys from imagekitio import ImageKit imagekit = ImageKit( public_key='your public_key', private_key='your private_key', url_endpoint = 'your url_endpoint' ) with open("image.jpg", mode="rb") as img: imgstr = base64.b64encode(img.read()) upload = imagekit.upload( file="https://ik.imagekit.io/ikmedia/red_dress_woman.jpeg", file_name="women_in_red.jpg", options=UploadFileRequestOptions( custom_metadata = {"brand":"Nike", "color":"red"} ), ) print("Upload url", upload) # Raw Response print(upload.response_metadata.raw) # print that uploaded file's ID print(upload.file_id)
use ImageKit\ImageKit; $public_key = "your_public_key"; $your_private_key = "your_private_key"; $url_end_point = "https://ik.imagekit.io/your_imagekit_id"; $sample_file_path = "/sample.jpg"; $imageKit = new ImageKit( $public_key, $your_private_key, $url_end_point ); // Upload Image - URL $uploadFile = $imageKit->uploadFile([ "file" => "https://ik.imagekit.io/ikmedia/red_dress_woman.jpeg", "fileName" => "women_in_red.jpg", "customMetadata" => [ "brand" => "Nike", "color" => "red", ] ]); echo ("Upload URL" . json_encode($uploadFile));
FileCreateRequest fileCreateRequest = new FileCreateRequest("https://ik.imagekit.io/ikmedia/red_dress_woman.jpeg", "women_in_red.jpg"); JsonObject jsonObjectCustomMetadata = new JsonObject(); jsonObjectCustomMetadata.addProperty("brand", "Nike"); jsonObjectCustomMetadata.addProperty("color", "red"); fileCreateRequest.setCustomMetadata(jsonObjectCustomMetadata); Result result=ImageKit.getInstance().upload(fileCreateRequest); System.out.println(result);
imagekitio = ImageKitIo::Client.new("your_private_key", "your_public_key", "your_url_endpoint") upload = imagekitio.upload_file( file: "https://ik.imagekit.io/ikmedia/red_dress_woman.jpeg", file_name: "women_in_red.jpg", custom_metadata: { "brand": "Nike", "color": "red" } )
url := "https://imagekit.io/image.jpg" resp, err := ik.Upload.Upload(ctx, url, uploader.UploadParam{ FileName: "women_in_red.jpg", CustomMetadata: `{"brand":"Nike", "color":"red"}`, })
var imagekit = new ImageKit({ publicKey : "your_public_api_key", privateKey : "your_private_api_key", urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/" }); var base64ImageRepresentation = "iVBORw0KGgoAAAAN"; FileCreateRequest ob2 = new FileCreateRequest { file = base64ImageRepresentation, fileName = Guid.NewGuid().ToString() }; Hashtable model = new Hashtable { { "brand", "Nike" }, { "color", "red" } }; ob2.customMetadata = model; Result resp = imagekit.Upload(ob2);
Applying extensions while uploading
curl -X POST "https://upload.imagekit.io/api/v1/files/upload" \ -u your_private_api_key: \ -F 'file=@/Users/username/Desktop/my_file_name.jpg' \ -F 'fileName=my_file_name.jpg' \ -F 'extensions=[{"name":"remove-bg","options":{"add_shadow":true,"bg_colour":"green"}},{"name":"google-auto-tagging","maxTags":5,"minConfidence":95}]'
var ImageKit = require("imagekit"); var fs = require('fs'); var imagekit = new ImageKit({ publicKey : "your_public_key", privateKey : "your_private_key", urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/" }); fs.readFile('image.jpg', function(err, data) { if (err) throw err; // Fail if the file can't be read. imagekit.upload({ file : data, //required fileName : "my_file_name.jpg", //required extensions: '[ { "name": "remove-bg", "options": { "add_shadow": true, "bg_colour": "green" } }, { "name": "google-auto-tagging", "maxTags": 5, "minConfidence": 95 } ]' }, function(error, result) { if(error) console.log(error); else console.log(result); }); });
import base64 import os import sys from imagekitio import ImageKit imagekit = ImageKit( public_key='your public_key', private_key='your private_key', url_endpoint = 'your url_endpoint' ) with open("image.jpg", mode="rb") as img: imgstr = base64.b64encode(img.read()) upload = imagekit.upload( file="https://ik.imagekit.io/ikmedia/red_dress_woman.jpeg", file_name="women_in_red.jpg", options=UploadFileRequestOptions( extensions = [{"name": "remove-bg", "options": {"add_shadow": True, "bg_color": "pink"}}, {"name": "google-auto-tagging", "minConfidence": 80, "maxTags": 10}] ), ) print("Upload url", upload) # Raw Response print(upload.response_metadata.raw) # print that uploaded file's ID print(upload.file_id)
use ImageKit\ImageKit; $public_key = "your_public_key"; $your_private_key = "your_private_key"; $url_end_point = "https://ik.imagekit.io/your_imagekit_id"; $sample_file_path = "/sample.jpg"; $imageKit = new ImageKit( $public_key, $your_private_key, $url_end_point ); // Upload Image - URL $uploadFile = $imageKit->upload([ "file" => "https://ik.imagekit.io/ikmedia/red_dress_woman.jpeg", "fileName" => "women_in_red.jpg", "extensions" => [ [ "name" => "remove-bg", "options" => [ "add_shadow" => true, "bg_colour" => "green" ] ], [ "name" => "google-auto-tagging", "maxTags" => 5, "minConfidence" => 95 ] ], ]); echo ("Upload URL" . json_encode($uploadFile));
FileCreateRequest fileCreateRequest =new FileCreateRequest("https://ik.imagekit.io/ikmedia/red_dress_woman.jpeg", "women_in_red.jpg"); JsonObject optionsInnerObject = new JsonObject(); optionsInnerObject.addProperty("add_shadow", true); optionsInnerObject.addProperty("bg_colour", "green"); JsonObject innerObject1 = new JsonObject(); innerObject1.addProperty("name", "remove-bg"); innerObject1.add("options", optionsInnerObject); JsonObject innerObject2 = new JsonObject(); innerObject2.addProperty("name", "google-auto-tagging"); innerObject2.addProperty("minConfidence", 5); innerObject2.addProperty("maxTags", 95); JsonArray jsonArray = new JsonArray(); jsonArray.add(innerObject1); jsonArray.add(innerObject2); fileCreateRequest.setExtensions(jsonArray); Result result=ImageKit.getInstance().upload(fileCreateRequest); System.out.println(result);
import ( "github.com/imagekit-developer/imagekit-go/extension" "github.com/imagekit-developer/imagekit-go/api/uploader" ) const base64Image = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" resp, err := ik.Uploader.Upload(ctx, base64Image, uploader.UploadParam{ Extensions: []extension.IExtension{ extension.NewAutoTag(extension.AwsAutoTag, 0, 10), extension.NewRemoveBg(extension.RemoveBgOption{}), }, })
var imagekit = new ImageKit({ publicKey : "your_public_api_key", privateKey : "your_private_api_key", urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/" }); var base64ImageRepresentation = "iVBORw0KGgoAAAAN"; FileCreateRequest ob2 = new FileCreateRequest { file = base64ImageRepresentation, fileName = Guid.NewGuid().ToString() }; List<Extension> ext = new List<Extension>(); BackGroundImage bck1 = new BackGroundImage { name = "remove-bg", options = new options() { add_shadow = true, semitransparency = false, bg_image_url = "http://www.google.com/images/logos/ps_logo2.png" } }; AutoTags autoTags = new AutoTags { name = "google-auto-tagging", maxTags = 5, minConfidence = 95 }; ext.Add(bck1); ext.Add(autoTags); ob2.extensions = ext; Result resp = imagekit.Upload(ob2);
Applying pre & post transformations while uploading
curl -X POST "https://upload.imagekit.io/api/v1/files/upload" \ -u your_private_api_key: \ -F 'file=@/Users/username/Desktop/my_file_name.jpg' \ -F 'fileName=my_file_name.jpg' \ -F 'transformation={"pre":"rt-90", "post": [{"type": "transformation", "value": "bg-red"}]}
How to implement client-side file upload?
Here are the steps:
- The client-side application initiates a request to the backend to obtain authentication parameters. This request should be made to a secure API endpoint accessible only to authenticated users, safeguarding your ImageKit Media library from unauthorized access.
- The required parameters are generated on the backend using the private API key. This is explained below with examples in different programming languages.
- The client-side application then includes these security parameters in the payload of the upload API request.
Never publish your private key on client-side
The Private API key should be kept confidential and only stored on your servers.
Using ImageKit client-side and server-side SDKs, you can quickly implement upload functionality.
- On the backend, you can use the utility functions provided in all server-side SDKs to implement the secure API.
- On client-side applications, use ImageKit client-side SDKs to get started quickly. See examples.
Backend signature generation
var token = req.query.token || uuid.v4(); var expire = req.query.expire || parseInt(Date.now()/1000)+2400; var privateAPIKey = "your_private_key"; var signature = crypto.createHmac('sha1', privateAPIKey).update(token+expire).digest('hex'); res.set({ "Access-Control-Allow-Origin" : "*" }) res.status(200); res.send({ token : token, expire : expire, signature : signature })
var ImageKit = require("imagekit"); var fs = require('fs'); var imagekit = new ImageKit({ publicKey : "your_public_api_key", privateKey : "your_private_api_key", urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/" }); var authenticationParameters = imagekit.getAuthenticationParameters(); console.log(authenticationParameters);
import base64 import os import sys from imagekitio import ImageKit imagekit = ImageKit( public_key='your public_key', private_key='your private_key', url_endpoint = 'your url_endpoint' ) auth_params = imagekit.get_authentication_parameters() print("Auth params-", auth_params)
use ImageKit\ImageKit; $public_key = "your_public_key"; $your_private_key = "your_private_key"; $url_end_point = "https://ik.imagekit.io/your_imagekit_id"; $sample_file_path = "/sample.jpg"; $imageKit = new ImageKit( $public_key, $your_private_key, $url_end_point ); $authenticationParameters = $imageKit->getAuthenticationParameters(); echo("Auth params : " . json_encode($authenticationParameters));
Client-side file upload examples
The example below demonstrates only basic usage. Refer to these examples to learn about different use cases. The only difference between client-side and server-side uploads is how API authentication works.
Make sure you have implemented the secure API in the backend that can return the signature
, one-time token
, and expire
parameters.
The best way is to follow quick start guides for your programming language.
<form action="#" onsubmit="upload()"> <input type = "file" id="file1" /> <input type = "submit" /> </form> <script type="text/javascript" src="../dist/imagekit.js"></script> <script> /* SDK initialization */ const imagekit = new ImageKit({ publicKey: "your_public_api_key", urlEndpoint: "https://ik.imagekit.io/your_imagekit_id", }); // Upload function internally uses the ImageKit.io javascript SDK async function upload(data) { const file = document.getElementById("file1"); const authenticationEndpoint = "https://www.yourserver.com/auth"; const authResponse = await fetch(authenticationEndpoint, { method: "GET", // You can also pass headers and validate the request source in the backend, or you can use headers for any other use case. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your-access-token', 'CustomHeader': 'CustomValue' }, }); if (!authResponse.ok) { throw new Error("Failed to fetch auth details"); } const authData = await authResponse.json(); imagekit.upload({ file: file.files[0], fileName: "abc.jpg", tags: ["tag1"], token: authData.token, signature: authData.signature, expire: authData.expire, }, function(err, result) { console.log(imagekit.url({ src: result.url, transformation : [{ height: 300, width: 400}] })); }) } </script>
<form action="#" onsubmit="upload()"> <input type="file" id="file1" /> <input type="submit" /> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script> // This endpoint should be implemented on your server as shown above const authenticationEndpoint = "https://www.yourserver.com/auth"; function upload() { var file = document.getElementById("file1"); var formData = new FormData(); formData.append("file", file.files[0]); formData.append("fileName", "abc.jpg"); formData.append("publicKey", "your_public_api_key"); // Let's get the signature, token and expire from server side $.ajax({ url : authenticationEndpoint, method : "GET", dataType : "json", // You can also pass headers and validate the request source in the backend, or you can use headers for any other use case. headers: { 'Authorization': 'Bearer your-access-token', 'CustomHeader': 'CustomValue' }, success : function(body) { formData.append("signature", body.signature || ""); formData.append("expire", body.expire || 0); formData.append("token", body.token); // Now call ImageKit.io upload API $.ajax({ url : "https://upload.imagekit.io/api/v1/files/upload", method : "POST", mimeType : "multipart/form-data", dataType : "json", data : formData, processData : false, contentType : false, error : function(jqxhr, text, error) { console.log(error) }, success : function(body) { console.log(body) } }); }, error : function(jqxhr, text, error) { console.log(arguments); } }); } </script>
import React from 'react'; import { IKContext, IKUpload } from 'imagekitio-react' function App() { const publicKey = "your_public_api_key"; const urlEndpoint = "https://ik.imagekit.io/your_imagekit_id"; const authenticator = async () => { try { // You can also pass headers and validate the request source in the backend, or you can use headers for any other use case. const headers = { 'Authorization': 'Bearer your-access-token', 'CustomHeader': 'CustomValue' }; const response = await fetch('server_endpoint', { headers }); if (!response.ok) { const errorText = await response.text(); throw new Error(`Request failed with status ${response.status}: ${errorText}`); } const data = await response.json(); const { signature, expire, token } = data; return { signature, expire, token }; } catch (error) { throw new Error(`Authentication request failed: ${error.message}`); } }; return ( <div className="App"> <p>To use this funtionality please remember to setup the server</p> <IKContext publicKey={publicKey} urlEndpoint={urlEndpoint} authenticator={authenticator} > <IKUpload fileName="abc.jpg" tags={["tag1"]} useUniqueFileName={true} isPrivateFile= {false} /> </IKContext> </div> ); } export default App;
<template> <div class="sample-app"> <p>Upload</p> <IKContext :publicKey="publicKey" :urlEndpoint="urlEndpoint" :authenticator="authenticator" > <IKUpload fileName="abc.jpg" v-bind:tags="['tag1']" v-bind:responseFields="['tags']"/> </IKContext> <p>To use this funtionality please remember to setup the server</p> </div> </template> <script> import { IKContext, IKUpload } from "imagekitio-vue"; export default { name: "app", components: { IKContext, IKUpload }, data() { return { urlEndpoint: "https://ik.imagekit.io/your_imagekit_id", publicKey: "your_public_api_key" }; }, methods: { authenticator() { return new Promise((resolve, reject) => { const headers = { 'Authorization': 'Bearer your-access-token', 'CustomHeader': 'CustomValue' }; var url = process.env.VUE_APP_YOUR_AUTH_ENDPOINT; // Make the Fetch API request fetch(url, { method: "GET", mode: "cors", headers }) // Enable CORS mode .then((response) => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then((body) => { var obj = { signature: body.signature, expire: body.expire, token: body.token, }; resolve(obj); }) .catch((error) => { reject([error]); }); }); }, }, }; </script>
Upload API Checks
The checks
parameter can be used to run server-side checks before files are uploaded to Media Library.
For requests involving pre-transformations on video files, checks will run asynchronously after the file has been transformed & before its uploaded to your Media Library.
You'll get an upload.pre-transform.error webhook event in case the check fails or an error occurs.
Note: Checks don't run on the post-transformations generated for an asset.
Basic examples
You can add a check that'll limit uploads to the marketing
folder and its sub-folders.
"request.folder" : "marketing/"
Remember to enclose the field you're running checks on in quotes like
"request.folder"
in the above example.
You can combine multiple conditions using the AND
and OR
operators. For example:
"file.size" <= "50MB" AND "mediaMetadata.height" <= 2000
This check will limit upload to file sizes below 50MB and height lesser than 2000px.
You can use parenthesis (
and )
to group multiple queries and create complex search filters. For example:
("request.customMetadata.size" = "XL" OR "request.customMetadata.size" = "L") AND ("request.tags" IN ["apparels"])
Check based on custom metadata
To run checks on custom metadata fields, prefix the field name with request.customMetadata.
.
For eg: If you want to run a check on a custom metadata field named quantity
, specify the field as request.customMetadata.quantity
.
Supported Fields
Field | Supported Operators | Examples |
---|---|---|
request.fileName | = , NOT = , : , IN , NOT IN | Accepts a string value in quotes.
|
request.useUniqueFileName | = , NOT = | Accepts a boolean value i.e., true or false without quotes. "request.useUniqueFileName" = true will only allow requests that have useUniqueFileName set to true . |
request.tags | IN , NOT IN | Accepts an array of string values.
|
request.folder | = , NOT = , : , IN , NOT IN | Accepts a string value in quotes.
|
request.isPrivateFile | = , NOT = | Accepts a boolean value i.e., true or false without quotes. "request.isPrivateFile" = true will only allow requests that have isPrivateFile set to true . |
request.isPublished | = , NOT = | Accepts a boolean value i.e., true or false without quotes."request.isPublished" = false will only allow requests that have isPublished set to false . |
request.customCoordinates | = , NOT = , : , IN , NOT IN | Accepts a string value in quotes. "request.customCoordinates" = "10,10,500,300" will not allow files that don't have the custom coordinate value set to 10,10,500,300 . |
request.webhookUrl | = , NOT = , : , IN , NOT IN | Accepts a string value in quotes. "request.webhookUrl" : "https://" will prevent URLs without HTTPS from being used. |
request.overwriteFile | = , NOT = | Accepts a boolean value i.e., true or false without quotes. "request.overwriteFile" = false will only allow requests that have overwriteFile set to false . |
request.overwriteAITags | = , NOT = | Accepts a boolean value i.e., true or false without quotes. "request.overwriteAITags" = false will only allow requests that have overwriteAITags set to false . |
request.overwriteTags | = , NOT = | Accepts a boolean value i.e., true or false without quotes. "request.overwriteTags" = false will only allow requests that have overwriteTags set to false . |
request.overwriteCustomMetadata | = , NOT = | Accepts a boolean value i.e., true or false without quotes. "request.overwriteCustomMetadata" = false will only allow requests that have overwriteCustomMetadata set to false . |
file.size | = , > , >= , < , <= | Accepts a numeric value e.g. 500 , 200 or string e.g. 1mb , 10kb .
|
file.mime | = , NOT = , : , IN , NOT IN | Accepts a string value e.g. image/webp , video/mp4 .
|
mediaMetadata.width | = , > , >= , < , <= | Accepts a numeric value. "mediaMetadata.width" < 550 will prevent media files with width lesser than 550px from being uploaded. |
mediaMetadata.height | = , > , >= , < , <= | Accepts a numeric value. "mediaMetadata.height" < 550 will prevent media files with height lesser than 550px from being uploaded. |
mediaMetadata.duration | = , > , >= , < , <= | Accepts a numeric value (in seconds). Only applicable for video-type assets. "mediaMetadata.duration" > 5 will only allow files with duration larger than 5 seconds. |
mediaMetadata.videoCodec | = , NOT = , : , IN , NOT IN | Accepts a string value e.g. h264 , vp8 . Only applicable for video-type assets.
|
mediaMetadata.audioCodec | = , NOT = , : , IN , NOT IN | Accepts a string value e.g. aac , mp3 . Only applicable for video-type assets. "mediaMetadata.audioCodec" = "aac" will only allow files with the audio codec aac . |
mediaMetadata.bitRate | = , > , >= , < , <= | Accepts a numeric value. Only applicable for video-type assets. "mediaMetadata.bitRate" < 10000 will only allow files with bitrate lesser than 10000. |
Custom metadata Text type field | = , NOT = , IN , NOT IN , : | Accepts a string value in quotes.
|
Custom metadata Textarea type field | = , NOT = , IN , NOT IN , : | Accepts a string value in quotes.
|
Custom metadata Date type field | = , NOT = , IN , NOT IN , > , >= , < , <= | Accepts a string value in ISO 8601 format.
|
Custom metadata Number type field | = , NOT = , IN , NOT IN , > , >= , < , <= | Accepts a numeric value. "request.customMetadata.quantitySold" > 200 will only allow files with quantitySold value greater than 200. |
Custom metadata Boolean type field | = , NOT = | Accepts a boolean value i.e., true or false without quotes. "request.customMetadata.active" = true will only allow files with the active value equal to true . |
Custom metadata SingleSelect type | = , NOT = , IN , NOT IN , : , > , >= , < , <= | Accepts boolean, numeric, or string values.
|
Custom metadata MultiSelect type | IN , NOT IN | Accepts an array of boolean, numeric, or string values.
|
Examples
Here are some example requests to understand the API usage.
Limiting file size
curl -X POST "https://upload.imagekit.io/api/v1/files/upload" \ -u your_private_api_key: \ -F 'file=@/Users/username/Desktop/my_file_name.jpg' \ -F 'fileName=my_file_name.jpg' \ -F "checks='file.size' < '1MB'"
Limiting mime-type
curl -X POST "https://upload.imagekit.io/api/v1/files/upload" \ -u your_private_api_key: \ -F 'file=@/Users/username/Desktop/my_file_name.jpg' \ -F 'fileName=my_file_name.jpg' \ -F "checks='file.mime' IN ['image/jpeg', 'image/png', 'image/svg+xml']"
Limiting media dimensions
curl -X POST "https://upload.imagekit.io/api/v1/files/upload" \ -u your_private_api_key: \ -F 'file=@/Users/username/Desktop/my_file_name.jpg' \ -F 'fileName=my_file_name.jpg' \ -F "checks='mediaMetadata.height' <= 300 AND 'mediaMetadata.width' <= 500"