Upload.js Docs
Quick start
Upload.js provides out-the-box, end-to-end file upload functionality for your web app.
Install Upload.js
Install Upload.js via a script tag or package manager:
Uploading files
To create a file upload button on your web page, copy this code:
Downloading files
To download your file, append its file ID to Upload's base URL. This allows you to store the file ID in your database rather than the entire URL. Upload.js includes a helper method:
const upload = new Upload({ ... })
const fileId = "AYU81093TgPQauaR";
upload.url(fileId); // "https://upcdn.io/AYU81093TgPQauaR"
Transforming files
Use transformations to resize/crop/convert images, and more:
Transformations are created in the Upload Dashboard.
Transformations are cached. If you change a transformation's parameters, you must clear the transformation's cache to see those changes applied to previously-transformed files.
To protect you against distributed denial of service (DDOS) attacks, Upload's transformations cannot be parameterized via the URL.
This prevents malicious users from executing an unlimited number of transformations against a file, potentially depleting your monthly CPU quota. Since transformation results are cached and transformation URLs are non-parameterizable, there's a hard limit on how many transformations can be run against your account at any given time.
Ready to start using Upload.js? Get Started
API Reference
Upload constructor
Only one instance of Upload should be instantiated per application: we recommend instantiating it at the start of your application and then exporting it.
The only mandatory configuration parameter is your Upload API key:
const upload = new Upload({
apiKey: "free"
})
Name | Default | Required | Description |
---|---|---|---|
apiKey | - | Yes | A publishable API key from your account. There are two types of API key: publishable and secret. Upload.js must be configured with a publishable API key. |
logging | false | No | Enables debug logging to the console. |
Upload methods
The createFileInputHandler method
This method returns a function that can be used as the onchange function for a file input element — it's the same function used in the Quick Start examples above.
const upload = new Upload({
apiKey: "free"
})
const onFileSelected =
upload.createFileInputHandler({
onUploaded: ({ fileUrl, fileId }) => {
// -----------------------------------------
// File successfully uploaded to upload.io!
// -----------------------------------------
// Send the file ID to your API, for example,
// to set it as the profile picture for a user.
// -----------------------------------------
console.log(`File uploaded to: ${fileUrl}`);
}
});
Parameters for createFileInputHandler
Name | Default | Required | Description |
---|---|---|---|
onUploaded | - | Yes | Fired when the upload succeeds: onUploaded: ( |
onError | - | No | Fired when the upload fails: onError: (error: any) => void
|
onBegin | - | No | Fired when the upload begins: onBegin: (
|
onProgress | - | No | Fired at regular intervals during the upload: onProgress: (
|
tags | - | No | Tags to associate with the file: tags: [
|
The uploadFile method
Alternatively if you have the file object already, you can use uploadFile:
const upload = new Upload({
apiKey: "free"
})
//
// ALTERNATIVE APPROACH:
//
const fileObject = event.target.files[0];
const { fileUrl, fileId } = await upload.uploadFile({
file: fileObject
});
// -----------------------------------------
// File successfully uploaded to upload.io!
// -----------------------------------------
// Send the file ID to your API, for example,
// to set it as the profile picture for a user.
// -----------------------------------------
console.log(`File uploaded to: ${fileUrl}`);
}
Parameters for uploadFile
Name | Default | Required | Description |
---|---|---|---|
file | - | Yes | File object extracted from a file input event. |
onBegin | - | No | Fired when the upload begins: onBegin: (
|
onProgress | - | No | Fired at regular intervals during the upload: onProgress: (
|
tags | - | No | Tags to associate with the file: tags: [
|
Associating file tags
Specifying a file tag is optional, but we recommend it:
const upload = new Upload({
apiKey: "free"
})
const onFileSelected =
upload.createFileInputHandler({
tags: [
"users/joe_bloggs/types/profile_picture",
"types/profile_picture"
],
onUploaded: ({ fileUrl, fileId }) => {
console.log(`File uploaded to: ${fileUrl}`);
}
});
Displaying progress
To display file upload progress:
const upload = new Upload({
apiKey: "free"
})
const onFileSelected =
upload.createFileInputHandler({
onProgress: ({ bytesSent, bytesTotal }) => {
console.log(`${bytesSent / bytesTotal}% complete`)
},
onUploaded: ({ fileUrl, fileId }) => {
console.log(`File uploaded to: ${fileUrl}`);
}
});
Cancelling an upload
To cancel an upload that's been started:
const upload = new Upload({
apiKey: "free"
})
const onFileSelected =
upload.createFileInputHandler({
onBegin: ({ cancel }) => {
//
// You should save 'cancel' to a variable then call it
// if/when the user clicks cancel in your UI: calling it
// will cancel the upload.
//
// cancel()
//
},
onUploaded: ({ fileUrl, fileId }) => {
console.log(`File uploaded to: ${fileUrl}`);
}
});
Access-protected files
You can restrict access such that only authenticated users of your web app can perform uploads and/or downloads.
To do this, complete the following steps:
Create a private/public RSA key pair:
ssh-keygen -t rsa -b 4096 -m PEM -f jwt_rs256.key -q -N ""openssl rsa -in jwt_rs256.key -pubout -outform PEM -out jwt_rs256.key.pubcat jwt_rs256.keycat jwt_rs256.key.pub- Add the public key to your Upload account via the Upload Dashboard.
- Make sure your backend API has access to the private key.
- Add a new endpoint to your backend API:
HTTP verb: GET
Path: anything
Response content-type: text/plain
Response body: an encoded JWT (e.g. eyJhbGci1NiJ9.e35gDeaAu...)
The JWT must be signed using the private key from step (1) with the RS256 algorithm.
The JWT payload must use this exact structure:
{
iat: number; // Token creation timestamp (epoch seconds).
exp: number; // Token expiration timestamp (epoch seconds).
sub: string; // Current user ID or username.
access: {
upload: boolean; // Can the user upload files?
download: boolean | { // Can the user download files?
tags?: string[]; // Limit downloads to certain files.
};
};
}
Call beginAuthSession on upload-js after the user signs-in to your web app:
const { Upload } = require("upload-js")
const upload = new Upload({apiKey: "<YOUR_KEY_HERE>" })
...
// Call this on sign-in.
function onSignIn() {
// URL for your auth endpoint (from step 4 above).
const authUrl = "https://your-web-app/your-auth-url"
// Headers required by your API (e.g. 'authorization' header).
const authHeaders = () => Promise.resolve({
authorization: "some auth token"
})
// Wait for authentication to complete.
await upload.beginAuthSession(
authUrl,
authHeaders
)
}Enforce authenticated uploads and/or downloads via the Upload Dashboard: