Skip to content

Commit ddab979

Browse files
authored
Merge pull request #57 from imagekit-developer/dev
Dev
2 parents 05f6002 + 44aa4ac commit ddab979

File tree

13 files changed

+1000
-217
lines changed

13 files changed

+1000
-217
lines changed

README.md

+115-19
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@
1010
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
1111
[![Twitter Follow](https://img.shields.io/twitter/follow/imagekitio?label=Follow&style=social)](https://twitter.com/ImagekitIo)
1212

13-
ImageKit Javascript SDK allows you to use real-time [image resizing](https://docs.imagekit.io/features/image-transformations), [optimization](https://docs.imagekit.io/features/image-optimization), and [file uploading](https://docs.imagekit.io/api-reference/upload-file-api/client-side-file-upload) in the client-side.
13+
Javascript SDK for [ImageKit](https://imagekit.io/) provides URL generation for image & video resizing and provides an interface for file upload. This SDK is lightweight and you can also use this as an ES module.
1414

15-
This SDK is lightweight and has no dependency. You can also use this as an ES module.
15+
ImageKit is complete media storage, optimization, and transformation solution that comes with an [image and video CDN](https://imagekit.io/features/imagekit-infrastructure). It can be integrated with your existing infrastructure - storage like AWS S3, web servers, your CDN, and custom domain names, allowing you to deliver optimized images in minutes with minimal code changes.
1616

1717
## Installation
1818

@@ -85,6 +85,7 @@ Create a file `.env` using `sample.env` in the directory `samples/sample-app` an
8585
Now start the sample application by running:
8686

8787
```
88+
// Run it from project root
8889
yarn startSampleApp
8990
```
9091

@@ -95,7 +96,7 @@ You can use this SDK for URL generation and client-side file uploads.
9596

9697
**1. Using image path and image hostname or endpoint**
9798

98-
This method allows you to create a URL using the `path` where the image exists and the URL endpoint (`urlEndpoint`) you want to use to access the image. You can refer to the documentation [here](https://docs.imagekit.io/integration/url-endpoints) to read more about URL endpoints in ImageKit and the section about [image origins](https://docs.imagekit.io/integration/configure-origin) to understand about paths with different kinds of origins.
99+
This method allows you to create an URL to access a file using the relative file path and the ImageKit URL endpoint (`urlEndpoint`). The file can be an image, video, or any other static file supported by ImageKit.
99100

100101
```
101102
var imageURL = imagekit.url({
@@ -116,7 +117,7 @@ https://ik.imagekit.io/your_imagekit_id/endpoint/tr:h-300,w-400/default-image.jp
116117

117118
**2. Using full image URL**
118119

119-
This method allows you to add transformation parameters to an existing, complete URL that is already mapped to ImageKit using the `src` parameter. This method should be used if you have the complete URL mapped to ImageKit stored in your database.
120+
This method allows you to add transformation parameters to an absolute URL. For example, if you have configured a custom CNAME and have absolute asset URLs in your database or CMS, you will often need this.
120121

121122

122123
```
@@ -141,11 +142,11 @@ The `.url()` method accepts the following parameters
141142
| Option | Description |
142143
| :----------------| :----------------------------- |
143144
| urlEndpoint | Optional. The base URL to be appended before the path of the image. If not specified, the URL Endpoint specified at the time of SDK initialization is used. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/ |
144-
| path | Conditional. This is the path at which the image exists. For example, `/path/to/image.jpg`. Either the `path` or `src` parameter need to be specified for URL generation. |
145-
| src | Conditional. This is the complete URL of an image already mapped to ImageKit. For example, `https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg`. Either the `path` or `src` parameter need to be specified for URL generation. |
146-
| transformation | Optional. An array of objects specifying the transformation to be applied in the URL. The transformation name and the value should be specified as a key-value pair in the object. Different steps of a [chained transformation](https://docs.imagekit.io/features/image-transformations/chained-transformations) can be specified as different objects of the array. The complete list of supported transformations in the SDK and some examples of using them are given later. If you use a transformation name that is not specified in the SDK, it gets applied as it is in the URL. |
147-
| transformationPostion | Optional. The default value is `path` that places the transformation string as a path parameter in the URL. It can also be specified as `query` which adds the transformation string as the query parameter `tr` in the URL. If you use `src` parameter to create the URL, then the transformation string is always added as a query parameter. |
148-
| queryParameters | Optional. These are the other query parameters that you want to add to the final URL. These can be any query parameters and not necessarily related to ImageKit. Especially useful if you want to add some versioning parameter to your URLs. |
145+
| path | Conditional. This is the path at which the image exists. For example, `/path/to/image.jpg`. Either the `path` or `src` parameter needs to be specified for URL generation. |
146+
| src | Conditional. This is the complete URL of an image already mapped to ImageKit. For example, `https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg`. Either the `path` or `src` parameter needs to be specified for URL generation. |
147+
| transformation | Optional. An array of objects specifying the transformation to be applied in the URL. The transformation name and the value should be specified as a key-value pair in the object. Different steps of a [chained transformation](https://docs.imagekit.io/features/image-transformations/chained-transformations) can be specified as different objects of the array. The complete list of supported transformations in the SDK and some examples of using them are given later. If you use a transformation name that is not specified in the SDK, it gets applied as it is in the URL. |
148+
| transformationPostion | Optional. The default value is `path`, which places the transformation string as a path parameter in the URL. It can also be specified as `query`, which adds the transformation string as the query parameter `tr` in the URL. If you use the `src` parameter to create the URL, then the transformation string is always added as a query parameter. |
149+
| queryParameters | Optional. These are the other query parameters that you want to add to the final URL. These can be any query parameters and are not necessarily related to ImageKit. Especially useful if you want to add some versioning parameters to your URLs. |
149150

150151
#### Examples of generating URLs
151152

@@ -189,7 +190,7 @@ https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=f-jpg%2Cpr
189190

190191
#### List of supported transformations
191192

192-
The complete list of transformations supported and their usage in ImageKit can be found [here](https://docs.imagekit.io/features/image-transformations). The SDK gives a name to each transformation parameter, making the code simpler and readable. If a transformation is supported in ImageKit, but a name for it cannot be found in the table below, then use the transformation code from ImageKit docs as the name when using in the `url` function.
193+
See the complete list of transformations supported in ImageKit [here](https://docs.imagekit.io/features/image-transformations). The SDK gives a name to each transformation parameter e.g. `height` for `h` and `width` for `w` parameter. It makes your code more readable. If the property does not match any of the following supported options, it is added as it is.
193194

194195
If you want to generate transformations in your application and add them to the URL as it is, use the `raw` parameter.
195196

@@ -256,18 +257,19 @@ If you want to generate transformations in your application and add them to the
256257

257258
### File Upload
258259

259-
The SDK provides a simple interface using the `.upload()` method to upload files to the ImageKit Media Library. It accepts all the parameters supported by the [ImageKit Upload API](https://docs.imagekit.io/api-reference/upload-file-api/client-side-file-upload).
260+
The SDK provides a simple interface using the `.upload()` method to upload files to the ImageKit Media Library.
260261

261-
The `upload()` method requires `file` and the `fileName` parameter.
262+
The `upload()` method requires mandatory `file` and the `fileName` parameter. In addition, it accepts all the parameters supported by the [ImageKit Upload API](https://docs.imagekit.io/api-reference/upload-file-api/client-side-file-upload).
262263

263264
Also, make sure that you have specified `authenticationEndpoint` during SDK initialization. The SDK makes an HTTP GET request to this endpoint and expects a JSON response with three fields, i.e. `signature`, `token`, and `expire`.
264265

265266
[Learn how to implement authenticationEndpoint](https://docs.imagekit.io/api-reference/upload-file-api/client-side-file-upload#how-to-implement-authenticationendpoint-endpoint) on your server.
266267

267268
You can pass other parameters supported by the ImageKit upload API using the same parameter name as specified in the upload API documentation. For example, to specify tags for a file at the time of upload, use the `tags` parameter as specified in the [documentation here](https://docs.imagekit.io/api-reference/upload-file-api/client-side-file-upload).
268269

269-
Sample usage
270-
```
270+
271+
#### Sample usage
272+
```html
271273
<form action="#" onsubmit="upload()">
272274
<input type="file" id="file1" />
273275
<input type="submit" />
@@ -287,6 +289,8 @@ Sample usage
287289
// Upload function internally uses the ImageKit.io javascript SDK
288290
function upload(data) {
289291
var file = document.getElementById("file1");
292+
293+
// Using Callback Function
290294
imagekit.upload({
291295
file: file.files[0],
292296
fileName: "abc1.jpg",
@@ -299,11 +303,25 @@ Sample usage
299303
}
300304
]
301305
}, function(err, result) {
302-
console.log(arguments);
303-
console.log(imagekit.url({
304-
src: result.url,
305-
transformation: [{ height: 300, width: 400}]
306-
}));
306+
console.log(result);
307+
})
308+
309+
// Using Promises
310+
imagekit.upload({
311+
file: file.files[0],
312+
fileName: "abc1.jpg",
313+
tags: ["tag1"],
314+
extensions: [
315+
{
316+
name: "aws-auto-tagging",
317+
minConfidence: 80,
318+
maxTags: 10
319+
}
320+
]
321+
}).then(result => {
322+
console.log(result);
323+
}).then(error => {
324+
console.log(error);
307325
})
308326
}
309327
</script>
@@ -312,3 +330,81 @@ Sample usage
312330
If the upload succeeds, `err` will be `null`, and the `result` will be the same as what is received from ImageKit's servers.
313331
If the upload fails, `err` will be the same as what is received from ImageKit's servers, and the `result` will be null.
314332

333+
## Tracking upload progress using custom XMLHttpRequest
334+
You can use a custom XMLHttpRequest object as the following to bind `progress` or any other events for a customized implementation.
335+
336+
```js
337+
var fileSize = file.files[0].size;
338+
var customXHR = new XMLHttpRequest();
339+
customXHR.upload.addEventListener('progress', function (e) {
340+
if (e.loaded <= fileSize) {
341+
var percent = Math.round(e.loaded / fileSize * 100);
342+
console.log(`Uploaded ${percent}%`);
343+
}
344+
345+
if(e.loaded == e.total){
346+
console.log("Upload done");
347+
}
348+
});
349+
350+
imagekit.upload({
351+
xhr: customXHR,
352+
file: file.files[0],
353+
fileName: "abc1.jpg",
354+
tags: ["tag1"],
355+
extensions: [
356+
{
357+
name: "aws-auto-tagging",
358+
minConfidence: 80,
359+
maxTags: 10
360+
}
361+
]
362+
}).then(result => {
363+
console.log(result);
364+
}).then(error => {
365+
console.log(error);
366+
})
367+
```
368+
369+
## Access request-id, other response headers, and HTTP status code
370+
You can access `$ResponseMetadata` on success or error object to access the HTTP status code and response headers.
371+
372+
```js
373+
// Success
374+
var response = await imagekit.upload({
375+
file: file.files[0],
376+
fileName: "abc1.jpg",
377+
tags: ["tag1"],
378+
extensions: [
379+
{
380+
name: "aws-auto-tagging",
381+
minConfidence: 80,
382+
maxTags: 10
383+
}
384+
]
385+
});
386+
console.log(response.$ResponseMetadata.statusCode); // 200
387+
388+
// { 'content-length': "300", 'content-type': 'application/json', 'x-request-id': 'ee560df4-d44f-455e-a48e-29dfda49aec5'}
389+
console.log(response.$ResponseMetadata.headers);
390+
391+
// Error
392+
try {
393+
await imagekit.upload({
394+
file: file.files[0],
395+
fileName: "abc1.jpg",
396+
tags: ["tag1"],
397+
extensions: [
398+
{
399+
name: "aws-auto-tagging",
400+
minConfidence: 80,
401+
maxTags: 10
402+
}
403+
]
404+
});
405+
} catch (ex) {
406+
console.log(response.$ResponseMetadata.statusCode); // 400
407+
408+
// {'content-type': 'application/json', 'x-request-id': 'ee560df4-d44f-455e-a48e-29dfda49aec5'}
409+
console.log(response.$ResponseMetadata.headers);
410+
}

package-lock.json

+3-4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+5-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "imagekit-javascript",
3-
"version": "1.4.3",
3+
"version": "1.5.0",
44
"description": "Javascript SDK for using ImageKit.io in the browser",
55
"main": "dist/imagekit.cjs.js",
66
"module": "dist/imagekit.esm.js",
@@ -68,5 +68,8 @@
6868
"bugs": {
6969
"url": "https://github.com/imagekit-developer/imagekit-javascript/issues"
7070
},
71-
"homepage": "https://github.com/imagekit-developer/imagekit-javascript#readme"
71+
"homepage": "https://github.com/imagekit-developer/imagekit-javascript#readme",
72+
"dependencies": {
73+
"regenerator-runtime": "^0.13.9"
74+
}
7275
}

samples/sample-app/views/index.pug

+27-12
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ html
1717
h4 Sample transformation with height: 300, width: 400:
1818
p
1919
img(src="")
20-
20+
2121
script(type='text/javascript' src="https://unpkg.com/imagekit-javascript/dist/imagekit.min.js")
2222
script.
2323
try {
@@ -26,25 +26,42 @@ html
2626
urlEndpoint: "!{urlEndpoint}",
2727
authenticationEndpoint: "!{authenticationEndpoint}"
2828
});
29-
29+
3030
window.imagekit = imagekit;
3131

32+
3233
function upload(e) {
3334
e.preventDefault();
3435
var file = document.getElementById("file1");
36+
var fileSize = file.files[0].size;
3537
var statusEl = document.getElementById("status");
36-
statusEl.innerHTML = "Uploading..."
38+
statusEl.innerHTML = "Uploading...";
39+
40+
// Use this if you want to track upload progress
41+
var customXHR = new XMLHttpRequest();
42+
customXHR.upload.addEventListener('progress', function (e) {
43+
if (e.loaded <= fileSize) {
44+
var percent = Math.round(e.loaded / fileSize * 100);
45+
console.log(`Uploaded ${percent}%`);
46+
}
47+
48+
if(e.loaded == e.total){
49+
console.log("Upload done");
50+
}
51+
});
52+
3753
imagekit.upload({
54+
xhr: customXHR, // Use this if you want to track upload progress
3855
file : file.files[0],
3956
fileName : file.files[0].name || "test_image.jpg",
4057
tags : ["test_tag_1"],
4158
//- extensions: [
42-
//- {
43-
//- name: "aws-auto-tagging",
44-
//- minConfidence: 80,
45-
//- maxTags: 10
46-
//- }
47-
//- ],
59+
//- {
60+
//- name: "aws-auto-tagging",
61+
//- minConfidence: 80,
62+
//- maxTags: 10
63+
//- }
64+
//- ],
4865
}, function(err, result) {
4966
if (err) {
5067
statusEl.innerHTML = "Error uploading image. "+ err.message;
@@ -60,15 +77,13 @@ html
6077

6178
var orig_img = document.querySelector("#orig_image > p > img");
6279
var trans_img = document.querySelector("#trans_image > p > img");
63-
80+
6481
orig_img.setAttribute("src", srcUrl);
6582
trans_img.setAttribute("src", transformedURL);
6683

6784
var el = document.getElementById('images')
6885
el.setAttribute("style", "");
6986
}
70-
71-
7287
});
7388
}
7489
} catch(ex) {

src/constants/errorMessages.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,10 @@ export default {
66
MISSING_UPLOAD_FILE_PARAMETER: { message: "Missing file parameter for upload", help: "" },
77
MISSING_UPLOAD_FILENAME_PARAMETER: { message: "Missing fileName parameter for upload", help: "" },
88
MISSING_AUTHENTICATION_ENDPOINT: { message: "Missing authentication endpoint for upload", help: "" },
9-
MISSING_PUBLIC_KEY : { message: "Missing public key for upload", help: "" },
9+
MISSING_PUBLIC_KEY: { message: "Missing public key for upload", help: "" },
1010
AUTH_ENDPOINT_TIMEOUT: { message: "The authenticationEndpoint you provided timed out in 60 seconds", help: "" },
1111
AUTH_ENDPOINT_NETWORK_ERROR: { message: "Request to authenticationEndpoint failed due to network error", help: "" },
12+
AUTH_INVALID_RESPONSE: { message: "Invalid response from authenticationEndpoint. The SDK expects a JSON response with three fields i.e. signature, token and expire.", help: "" },
1213
UPLOAD_ENDPOINT_NETWORK_ERROR: {
1314
message: "Request to ImageKit upload endpoint failed due to network error",
1415
help: "",

src/constants/supportedTransforms.ts

+5
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,11 @@ const supportedTransforms: { [key: string]: string } = {
281281
* @link https://docs.imagekit.io/features/image-transformations/resize-crop-and-other-transformations#original-image-orig
282282
*/
283283
original: "orig",
284+
285+
/**
286+
* @link https://docs.imagekit.io/features/image-transformations/conditional-transformations
287+
*/
288+
raw: "raw",
284289
}
285290

286291

0 commit comments

Comments
 (0)