Client side file upload

You can upload files to ImageKit.io media library directly from client-side in Javascript, or Android or iPhone app using signature based authentication.

Endpoint

Request structure (multipart/form-data)

Parameter

Description

file required

This field accepts three kind of values:

  • binary - You can send the content of the file as binary. This is used when a file is being uploaded from the browser.

  • base64 - Base64 encoded string of file content.

  • url - URL of the file from where to download the content before uploading. Downloading file from URL might take longer, so it is recommended that you pass the binary or base64 content of the file. Pass the full URL, for example - https://www.example.com/rest-of-the-image-path.jpg.

publicKey required

Your public API key.  Note: This field is only required when uploading the file from client-side. The only purpose of this is to identify your account.

signature required

HMAC-SHA1 digest of the token+expire using your ImageKit.io private API key as a key. Learn how to create signature below in the page.

Warning: Signature must be calculated on the server side. This field is required for authentication when uploading a file from client-side.

expire required

The time until your signature is valid. It must be a Unix time in less than 1 hour into the future. It should be in seconds.

token required

A unique value generated by the client, which will be used by the ImageKit.io server to recognize and prevent subsequent retries for the same request. We suggest using V4 UUIDs, or another random string with enough entropy to avoid collisions. Note: Sending a value which has been used in the past will result in a validation error. Even if your previous request resulted in an error, you should always send a new value for this field.

fileName required

The name with which the file has to be uploaded.

useUniqueFileName optional

Whether to use a unique filename for this file or not.

  • Accepts true or false.

  • If set true, ImageKit.io will add a unique suffix to the filename parameter to get a unique filename.

  • If set false, then the image is uploaded with the provided filename parameter and any existing file with the same name is replaced.

Default value - true

tags optional

Set the tags while uploading the file.

  • Comma-separated value of tags in format tag1,tag2,tag3. For example - t-shirt,round-neck,men

  • The maximum length of all characters should not exceed 500.

  • % is not allowed.

  • If this field is not specified and the file is overwritten, then the tags will be removed.

folder optional

The folder path (e.g. /images/folder/) in which the image has to be uploaded. If the folder(s) didn't exist before, a new folder(s) is created.

The folder name can contain:

  • Alphanumeric Characters: a-z , A-Z , 0-9

  • Special Characters: / _ and -

  • Using multiple / creates a nested folder.

Default value - /

isPrivateFile optional

Whether to mark the file as private or not. This is only relevant for image type files

  • Accepts true or false.

  • If set true, the file is marked as private which restricts access to the original image URL and unnamed image transformations without signed URLs. Without the signed URL, only named transformations work on private images

Default value - false

customCoordinates optional

Define an important area in the image. This is only relevant for image type files.

  • To be passed as a string with the x and y coordinates of the top-left corner, and width and height of the area of interest in format x,y,width,height. For example - 10,10,100,100

  • Can be used with fo-customtransformation.

  • If this field is not specified and the file is overwritten, then customCoordinates will be removed.

responseFields optional

Comma-separated values of the fields that you want ImageKit.io to return in response.For example, set the value of this field to tags,customCoordinates,isPrivateFile,metadata to get value of tags, customCoordinates, isPrivateFile , and metadata in the response.

Response code and structure (JSON)

In case of error, you will get an error code along with the error message. On successful upload, you will receive a 200 status code with uploaded file details in a JSON-encoded response body.

{
"fileId" : "598821f949c0a938d57563bd",
"name": "file1.jpg",
"url": "https://ik.imagekit.io/your_imagekit_id/images/products/file1.jpg",
"thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-media_library_thumbnail/images/products/file1.jpg",
"height" : 300,
"width" : 200,
"size" : 83622,
"filePath": "/images/products/file1.jpg",
"tags": ["t-shirt","round-neck","sale2019"],
"isPrivateFile" : false,
"customCoordinates" : null,
"fileType": "image"
}

Understanding response

The JSON-encoded response contains details of the file which can have the following properties:

Field

Description

fileId

Unique fileId. Store this fileld in your database, as this will be used to perform update action on this file.

name

The name of the uploaded file.

url

The URL of the file.

thumbnail

In case of an image, a small thumbnail URL.

height

Height of the uploaded image file. Only applicable when file type is image.

width

Width of the uploaded image file. Only applicable when file type is image.

size

Size of the uploaded file in bytes.

fileType

Type of file. It can either be image or non-image.

filePath

The path of the file uploaded. It includes any folder that you specified while uploading.

tags

Array of tags associated with the file.

isPrivateFile

Is the file marked as private. It can be either true or false.

customCoordinates

Value of custom coordinates associated with the image in format x,y,width,height.

metadata

The metadata of the upload file. Use fields property in request to get the metadata returned in response of upload API.

Signature generation for client-side file upload

signature is a string sent along with your upload request for authentication when using upload API from client-side. Generating it requires your ImageKit.io private API key, and hence should be generated on your backend.

The signature is HMAC-SHA1 digest of string token+expire using your ImageKit.io private API key as a key.

Here is how to generate signature on server-side using Node.js:

const crypto = require("crypto");
const uuidv4 = require('uuid/v4');
// your private API key e.g. private_LKSJDFOWI101212D03120
var privateAPIKey = "your_private_api_key";
// A unique key e.g. 06a7c148-e553-4a2a-80ca-10dd8ad7eb64
var token = uuidv4();
// E.g. 1567317691
var expire = parseInt(Date.now()/1000)+2400;
// E.g. 6c6addcb8c2d1ea742701dde59e64c4ef12843c9
console.log(crypto.createHmac('sha1', privateAPIKey).update(token+expire).digest('hex'));

Never publish your private key on client-side The Private API key should be kept confidential and only stored on your own servers.

Examples

Using ImageKit.io javascript SDK

You can use ImageKit.io javascript SDK for uploading files from the browser.

You can initialize the SDK, and upload field as:

HTML (client-side)
Node.js (server-side authenticationEndpoint implementaion)
HTML (client-side)
index.html
<form action="#" onsubmit="upload()">
<input type="file" id="file1" />
<input type="submit" />
</form>
<script type="text/javascript" src="../dist/imagekit.js"></script>
<script>
// SDK initilization
// authenticationEndpoint should be implemented on your server
var imagekit = new ImageKit({
publicKey : "your_public_api_key",
urlEndpoint : "https://ik.imagekit.io/your_imagekit_id",
authenticationEndpoint : "http://www.yourserver.com/auth"
});
// Upload function internally uses the ImageKit.io javascript SDK
function upload(data) {
var file = document.getElementById("file1");
imagekit.upload({
file : file.files[0],
fileName : "abc1.jpg",
tags : ["tag1"]
}, function(err, result) {
console.log(arguments);
console.log(imagekit.url({
src: result.url,
transformation : [{ HEIGHT: 300, WIDTH: 400}]
}));
})
}
</script>
Node.js (server-side authenticationEndpoint implementaion)
routes.js
// A typical implementation of authenticationEndpoint on server-side
const express = require('express');
const router = express.Router();
const auth = require('basic-auth')
const startupCacheManager = require("../startup/cacheManager");
const media = require("./admin/media");
const validate = require('../middleware/basicAuthValidator');
const uuidv4 = require('uuid/v4');
const crypto = require("crypto");
router.get("/auth", function(req, res) {
var token = req.query.token || uuidv4();
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.status(200);
res.send({
token : token,
expire : expire,
signature : signature
});
});
module.exports = router;

💡 SDK invokes authenticationEndpoint endpoint and expects signature, token and expire to be retuned in JSON format. The Node.js example below demonstrations how you can implement this endpoint.

Using jQuery.js

Initialize the jQuery and upload field as:

HTML (client-side)
Node.js (server-side authenticationEndpoint implementation)
HTML (client-side)
index.html
<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 endpoitn should be implemented on your server
var authenticationEndpoint = "https://yourdomain.com/auth";
function upload() {
var file = document.getElementById("file1");
var formData = new FormData();
formData.append("file", file);
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",
success : function(body) {
if(typeof callback != "function") return;
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>
Node.js (server-side authenticationEndpoint implementation)
routes.js
// A typical implementation of authenticationEndpoint on server-side
const express = require('express');
const router = express.Router();
const auth = require('basic-auth')
const startupCacheManager = require("../startup/cacheManager");
const media = require("./admin/media");
const validate = require('../middleware/basicAuthValidator');
const uuidv4 = require('uuid/v4');
const crypto = require("crypto");
router.get("/auth", function(req, res) {
var token = req.query.token || uuidv4();
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.status(200);
res.send({
token : token,
expire : expire,
signature : signature
});
});
module.exports = router;