Upload.js Docs

Installation

Install Upload.js by including the Upload.js script on your webpage or by installing it as a module, through a package manager like NPM or YARN:

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

Configuration

To get started, instantiate Upload with some basic configuration:

// 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.

Uploading

Creating a button

To create an upload button, add the following code to your webpage:

<input type="file" onchange="onFileSelected(event)" />
<input type="file" onChange={onFileSelected} />
<input id="upload-example" type="file" @change="onChange">

const uploadExample = new Vue({
  el: "#upload-example",
  methods: {
    onChange(event) {
      onFileSelected(event);
    }
  }
});
<input type="file" (change)="onChange($event)" />

onChange(event) {
  onFileSelected(event);
}

Uploading a file

Method #1: createFileInputHandler

To wire-up the upload button from the previous step, use createFileInputHandler:

// 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.

Method #2: uploadFile

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}`);
    }

  });

Downloading

To download your file, simply browse to its file URL (this can be constructed from the file ID):

https://files.upload.io/AYU81093TgPQauaR                        \____File ID___/\_______________File URL_______________/

When saving references to files in your database, we recommend saving the file ID rather than the full file URL: it's shorter, and the Upload REST API takes file IDs instead of URLs.

Getting a file's URL

To get a file URL from a file ID, you can use the url helper method:

// 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 fileId  = "AYU81093TgPQauaR";

const fileUrl = upload.url(fileId);

console.log(fileUrl); // "https://files.upload.io/AYU81093TgPQauaR"

Transforming a file

To transform a file, append the desired transformation's "slug" to the file URL:

https://files.upload.io/FILE_ID/TRANSFORMATION_SLUG

To find the "slug" for the transformation you want to use, go to the Upload Dashboard and browse the available transformations, then take note of the desired transformation's "slug".

The response from the URL will be the transformed file.

Defining a transformation

Transformations are easy to define in the Upload Dashboard.

Transformation definitions have the following structure:

NameRequiredDescription

name

Yes

The transformation name is also the URL slug. It must be unique across your account.

cacheKey

Yes

Transformed files are cached permanently. Changing the cacheKey of a transformation will cause subsequent requests to files through that transformation to be regenerated.

Changing the cacheKey does not automatically delete the old file cache: this allows you to change the cacheKey back at any time to resume serving the old cached files in the event of a mistake.

You may wish to periodically delete unused caches to free-up storage space.

This can be done through the Upload Dashboard.

scope.mime[]

Yes

Limits the transformation to files that have a MIME type that matches one or more of the MIME types specified here.

Wildcards are supported, e.g. image/*

The Upload Dashboard automatically sets this value to [*] on all new transformations -- i.e. the transformation will match all file types.

scope.tag[]

Yes

Limits the transformation to files that have a file tag that matches one or more of the file tags specified here.

Wildcards are supported, e.g. user_uploads/images/profile_pics/*

The Upload Dashboard automatically sets this value to [*] on all new transformations -- i.e. the transformation will match all file tags.

steps[]

Yes

Defines the sequence of steps that will be executed against files transformed with this transformation.

steps[].packageName

Yes

NPM package name for the code to run on this step.

See Upload Plugin SDK for instructions on how to write NPM packages that can be used in transformation steps.

steps[].packageVersion

Yes

NPM package version.

Supports exact versions only (i.e. no ^ or ~ prefixes).

steps[].params

Yes

Arbitrary JSON object representing parameters that may be required by the NPM package.

For example, an "image resize" package might require the following params:

{ width: 300, height: 200 }

Using a transformation

Once you know which transformation you want to use, append its "slug" to the file URL:

https://files.upload.io/FILE_ID/TRANSFORMATION_SLUG

The returned file will be the transformed file.

For example, if your transformation is called 300x200 and you wanted to transform the file with ID AYU81093TgPQauaR, then use the following URL:

https://files.upload.io/AYU81093TgPQauaR/300x200

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:

Congratulations! Users must now sign-in to your website to upload and/or download files!

You are using an outdated browser.

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