Data Types

Upload JavaScript SDK

Headless library for performing file uploads. No UI included. See the Upload Widget for a ready-made UI component.

Install

To install the Upload JavaScript SDK via NPM:

npm install upload-js

To install via YARN:

yarn install upload-js

To install via a script tag:

<script src="https://js.upload.io/upload-js/v2"></script>

Recommended: use this SDK to upload files from the browser (6KB package size).

Examples

Upload a File

To upload a file with the Upload JavaScript SDK:

1<html>
2 <head>
3 <script src="https://js.upload.io/upload-js/v2"></script>
4 <script>
5 // import { Upload } from "upload-js"
6 const upload = Upload({
7 apiKey: "free" // Replace "free" with your API key.
8 });
9
10 const onFileSelected = async event => {
11 const file = event.target.files[0];
12
13 try {
14 const { fileUrl, filePath } = await upload.uploadFile(
15 // Required.
16 file,
17
18 // Optional.
19 {
20 onBegin: ({ cancel }) => {
21 // Call 'cancel()' to stop the upload.
22 },
23 onProgress: ({ bytesSent, bytesTotal }) => {
24 // Use this to display progress.
25 },
26 metadata: {
27 // Up to 2KB of arbitrary JSON.
28 productId: 60891
29 },
30 tags: [
31 // Up to 25 tags per file.
32 "product_image"
33 ],
34 path: {
35 // See path variables: https://upload.io/docs/path-variables
36 folderPath: "/uploads/{UTC_YEAR}/{UTC_MONTH}/{UTC_DAY}",
37 fileName: "{UNIQUE_DIGITS_8}{ORIGINAL_FILE_EXT}"
38 }
39 }
40 );
41
42 // --------------------------------------------
43 // File successfully uploaded!
44 // --------------------------------------------
45 // The 'filePath' uniquely identifies the file,
46 // and is what you should save to your API.
47 // --------------------------------------------
48 alert(`File uploaded to: ${fileUrl}`);
49
50 } catch (e) {
51 alert(`Upload failed: ${e.message}`);
52 }
53 }
54 </script>
55 </head>
56 <body>
57 <input type="file" onchange="onFileSelected(event)" />
58 </body>
59</html>

See also: UploadJsParams and Path Variables

Live preview:

Download a File

To generate a file URL for an uploaded file:

1import { Upload } from "upload-js"
2const upload = Upload({ apiKey: "free" }); // Replace "free" with your API key.
3
4const filePath = "/uploads/example.jpg";
5const fileUrl = upload.url(filePath);
6// fileUrl = "https://upcdn.io/abc1234/raw/uploads/example.jpg"

Process a File

To generate a file URL for an uploaded file, with a file transformation applied:

1import { Upload } from "upload-js"
2const upload = Upload({ apiKey: "free" }); // Replace "free" with your API key.
3
4const filePath = "/uploads/example.jpg";
5const transformation = "thumbnail";
6const fileUrl = upload.url(filePath, { transformation });
7// fileUrl = "https://upcdn.io/abc1234/thumbnail/uploads/example.jpg"

Tip: Create transformations via the Upload Dashboard »

API Reference

uploadFile

Uploads a file to your account.

This method performs a multipart file upload internally, which provides better performance compared to BasicUpload and FormDataUpload.

Signature

function uploadFile(file: BlobOrFileObject, params?: UploadParams): Promise<UploadedFile>

Parameters

  1. file: BLOB or file from an <input type="file" onchange="..." /> event.

  2. params: UploadJsParams object (optional).

Result promise

Promise of type UploadedFile

Example

import { Upload } from "upload-js";
const upload = Upload({ apiKey: "free" }); // Replace "free" with your API key.
const onFileSelected = async (event) => {
const [ file ] = event.target.files;
const { fileUrl } = await upload.uploadFile(file, { onProgress });
alert(`File uploaded: ${fileUrl}`);
}
const onProgress = ({ progress }) => {
console.log(`File uploading: ${progress}% complete.`)
}
//
// <input type="file" onchange="onFileSelected(event)" />
//

Full example: Upload a File »

url

Gets the URL for an uploaded file (takes a filePath and returns a URL).

We recommend saving filePath values instead of fileUrl values to your database, as this allows you to change other parts of the URL in future (such as the URL's domain name — if you upgrade to a custom domain — or the "file transformation" part of the URL).

Signature

function url(filePath: string, urlParams?: { auth?: boolean; transformation?: string; }): string

Result

"https://upcdn.io/abc1234/thumbnail/uploads/example.jpg"

Example

const upload = Upload({ apiKey: "free" }); // Replace "free" with your API key.
const fileUrl = upload.url("/uploads/example.jpg", { transformation: "thumbnail" });
// fileUrl = "https://upcdn.io/abc1234/thumbnail/uploads/example.jpg"

beginAuthSession

Call this method once at the start of your application — after the user has been authenticated — if the user needs to download private files.

This will start a cookie-based auth session to allow users to download private files directly via the URL. For example, if your webpage contains <img> elements that reference private image files, you can use beginAuthSession to allow these images to render in the current browser tab, while keeping them inaccessible to unauthorized users.

Internally, the method works by periodically requesting JWT access tokens from your API, which are then stored in an Upload CDN cookie to allow downloads of the files granted by the JWT.

Signature

function beginAuthSession(authUrl: string, authHeaders: () => Promise<Record<string, string>>): Promise<void>

Prerequisites

Implement a backend API endpoint that generates a public/private key JWT, with its payload structured as an UploadJwt, and its public key certificate added to your JWT Certificates.

See: Authorization

Example

const upload = Upload({ apiKey: "free" }); // Replace "free" with your API key.
upload.beginAuthSession(
"https://your-api-domain.example.com/auth",
async () => ({
Authorization: "SomeAuthorizationHeaderRequiredByYourApi"
})
);

endAuthSession

Ends an authorized browser session, preventing the user from downloading further private files.

Signature

function endAuthSession(): Promise<void>

Prerequisites

Can only be called after a successful call to beginAuthSession.

Example

const upload = Upload({ apiKey: "free" }); // Replace "free" with your API key.
// User signs in:
upload.beginAuthSession(
"https://your-api-domain.example.com/auth",
async () => ({
Authorization: "SomeAuthorizationHeaderRequiredByYourApi"
})
);
// User downloads files:
// ...
// User signs out:
upload.endAuthSession();

Was this section helpful? Yes No

You are using an outdated browser.

This website requires a modern web browser -- the latest versions of these browsers are supported: