Upload.js Docs

Quick start

Upload.js provides out-the-box, end-to-end file upload functionality for your web app.

1 Install Upload.js

Install Upload.js via a script tag or package manager:

npm install upload-js
yarn add upload-js
<script src="https://js.upload.io/upload-js/v1"></script>

2 Uploading files

To create a file upload button on your web page, copy this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<html>
<head>
 <script src="https://js.upload.io/upload-js/v1"></script>
 <script>
   var upload = new Upload({apiKey: "..."})
   var uploadFile = upload.createFileInputHandler({
     onUploaded: ({ fileUrl, fileId }) => {
       alert(`File uploaded! ${fileUrl}`);
     }
   });
 </script>
</head>
<body>
 <input type="file" onchange="uploadFile(event)" />
</body>
</html>

3 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 } = require("upload-js")
const upload     = new Upload({ ... })
const fileId     = "AYU81093TgPQauaR";

upload.url(fileId); // "https://files.upload.io/AYU81093TgPQauaR"

4 Transforming files (optional)

Use transformations to resize/crop/convert images, and more:

https://files.upload.io/AYU81093TgPQauaR/my_amazing_transformation\___Upload Base URL___/ \____File ID___/ \__Transformation Slug__/\______________________Transformed File URL______________________/

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:

// Include this line if you installed Upload.js via NPM or Yarn.const { Upload } = require("upload-js")

const upload = new Upload({
  apiKey: "YOUR_API_KEY_HERE"
})
NameDefaultRequiredDescription

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.

// Include this line if you installed Upload.js via NPM or Yarn.const { Upload } = require("upload-js")

const upload = new Upload({
  apiKey: "YOUR_API_KEY_HERE"
})

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
NameDefaultRequiredDescription

onUploaded

-

Yes

Fired when the upload succeeds:

onUploaded: (
  result: {
    fileId: string,
    fileUrl: string,
  }
) => void

onError

-

No

Fired when the upload fails:

onError: (error: any) => void

  • If you don't specify this handler then any errors will be logged to the console.

onBegin

-

No

Fired when the upload begins:

onBegin: (
  params: {
    cancel: () => void
  }
) => void

onProgress

-

No

Fired at regular intervals during the upload:

onProgress: (
  status: {
    bytesSent: number,
    bytesTotal: number
  }
) => void

tags

-

No

Tags to associate with the file:

tags: [
  "users/123/types/profile_pic",
  "types/profile_pic",
  {
    name: "some/other/tag",
    searchable: false
  }
]

  • Tags can be strings or objects (per the example).
  • Strings assume searchable: true, meaning objects are only used to addsearchable: false tags.
  • Each file can have up to 25 tags: up to 10 tags can be searchable.
  • Searchable tags can be prefix-searched in the Upload Dashboard.

The uploadFile method

Alternatively if you have the file object already, you can use uploadFile:

// Include this line if you installed Upload.js via NPM or Yarn.const { Upload } = require("upload-js")

const upload = new Upload({
  apiKey: "YOUR_API_KEY_HERE"
})

//
// ALTERNATIVE APPROACH:
//

const onFileSelected = async event => {
  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
NameDefaultRequiredDescription

file

-

Yes

File object extracted from a file input event.

onBegin

-

No

Fired when the upload begins:

onBegin: (
  params: {
    cancel: () => void
  }
) => void

onProgress

-

No

Fired at regular intervals during the upload:

onProgress: (
  status: {
    bytesSent: number,
    bytesTotal: number
  }
) => void

tags

-

No

Tags to associate with the file:

tags: [
  "users/123/types/profile_pic",
  "types/profile_pic",
  {
    name: "some/other/tag",
    searchable: false
  }
]

  • Tags can be strings or objects (per the example).
  • Strings assume searchable: true, meaning objects are only used to addsearchable: false tags.
  • Each file can have up to 25 tags: up to 10 tags can be searchable.
  • Searchable tags can be prefix-searched in the Upload Dashboard.

Associating file tags

Specifying a file tag is optional, but we recommend it:

// Include this line if you installed Upload.js via NPM or Yarn.const { Upload } = require("upload-js")

const upload = new Upload({
  apiKey: "YOUR_API_KEY_HERE"
})

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:

// Include this line if you installed Upload.js via NPM or Yarn.const { Upload } = require("upload-js")

const upload = new Upload({
  apiKey: "YOUR_API_KEY_HERE"
})

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:

// Include this line if you installed Upload.js via NPM or Yarn.const { Upload } = require("upload-js")

const upload = new Upload({
  apiKey: "YOUR_API_KEY_HERE"
})

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:

  1. 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
  2. Add the public key to your Upload account via the Upload Dashboard.
  3. Make sure your backend API has access to the private key.
  4. 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.
            };
          };
        }
  5. 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
      )
    }
  6. Enforce authenticated uploads and/or downloads via the Upload Dashboard:

You are using an outdated browser.

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