JavaScript File Picker

Getting Started

To start with Web File Picker, you will need the Filestack application and API key. Please read our Quick Start guide that explains basic vocabulary and features available at Filestack. File Picker is part of our open-source JavaScript SDK.

Opening File Picker

To integrate Filestack File Picker with your web application, simply include our JavaScript SDK UMD module in your code:

<script src="//static.filestackapi.com/filestack-js/3.x.x/filestack.min.js"></script>

Read about other ways of including our JavaScript SDK from our JavaScript SDK Reference.

Once the Filestack code is included, you can configure the client with your API Key. The code below is all that is required to open the default File Picker.

const client = filestack.init(YOUR_API_KEY);
client.picker().open();

Picker Response

For each uploaded file, PickerFileMetadata object is created with file details, a unique handle, and a CDN URL. This object can be accessed using callbacks when the upload is finished.

PickerFileMetadata interface
{
  "filename": "myfile.png",
  "handle": "AFrHW1QRsWxmu5ZLU2qg",
  "mimetype": "image/png",
  "originalPath": "picker_transformation.png",
  "size": 1277297,
  "source": "local_file_system",
  "url": "https://cdn.filestackcontent.com/AFrHW1QRsWxmu5ZLU2qg",
  "uploadId": "cfcc198e63b7328c17f09f1af519fcdf",
  "originalFile": {
    "name": "myfile",
    "type": "image/png",
    "size": 1277297
  },
  "status": "Stored"
}
PARAM TYPE DESCRIPTION
handle string Filestack's unique identifier of the uploaded file.
url string Unique CDN url to access uploaded file.
filename string Name of the uploaded file. This can be changed in the PickerOptions.
mimetype string Mimetype of the uploaded file.
size int Size of the uploaded file.
source string Source of the uploaded file.
status string Status of the upload. Can be either Stored or InTransit for CIN and FII.
originalFile Object Object representing original file, its name, type, and size.
originalPath string Original path from where the file was uploaded.
uploadID string Uniqe id of the upload for debugging.
PickerResponse interface

When using onUploadDone callback, you will receive PickerResponse that represents state of all the files that were uploaded during given Picker session. Both filesUploaded and filesFailed are arrays of PickerFileMetadata objects explained above. For example:

{
   "filesUploaded":[
      {
         "filename":"myfile.png",
         "handle":"AFrHW1QRsWxmu5ZLU2qg",
         "mimetype":"image/png",
         "originalPath":"picker_transformation.png",
         "size":1277297,
         "source":"local_file_system",
         "url":"https://cdn.filestackcontent.com/AFrHW1QRsWxmu5ZLU2qg",
         "uploadId":"cfcc198e63b7328c17f09f1af519fcdf",
         "originalFile":{
            "name":"myfile",
            "type":"image/png",
            "size":1277297
         },
         "status":"Stored"
      }
   ],
   "filesFailed":[

   ]
}

Picker Options

While the default File Picker implementation is suitable for basic use cases, you can easily configure your instance in multiple ways. To do that, you can use the PickerOptions interface.

The most used options are:

  • Picker Options - master set of options you can use to specify default File Picker behavior and limitations.
  • Store Options - control where and how files should be stored.
  • Upload Options - control how your files are uploaded to your storage destination.
  • Transformation Options - control how your users transform files before they are stored.
  • Accept Function - control file’s mimetype acceptance criteria.

We will present the most important options below, but the full specification can be found in our JavaScript SDK Reference.

PARAM TYPE DESCRIPTION
disableThumbnails boolean Using this parameter, you can disable local image thumbnail previews in the summary screen.
disableTransformer boolean Using this parameter, you can disable the ability to edit images.
displayMode string Using this parameter, you can choose the Picker display mode. Possible values are 'inline', 'overlay' and 'dropPane'.
dropPane interface Using this parameter, you can configure the drop pane behavior, when the displayMode is set as 'dropPane'.
exposeOriginalFile boolean Using this parameter, you can choose if the originalFile metadata will be the actual File object instead of a POJO.
globalDropZone boolean Using this parameter, you can toggle the drop zone to be active on all views. By default, it is active only on local file source.
hideModalWhenUploading boolean Using this parameter, you can choose if the picker modal UI should be hidden once uploading begins.
imageDim array Using this parameter, you can specify image dimensions of the file. It works only for JPEG, PNG, and BMP files. Local and cropped images will be resized (upscaled or downscaled) to the specified dimensions before uploading while maintaing the original height to width ratio.
imageMax array Using this parameter, you can specify the maximum image dimensions of the file. It works only for JPEG, PNG, and BMP files. Images bigger than the specified dimensions will be resized to the maximum size while maintaining the original aspect ratio.
imageMin array Using this parameter, you can specify the minimum image dimensions of the file. It works only for JPEG, PNG, and BMP files. Images smaller than the specified dimensions will be resized to the minimum size while maintaining the original aspect ratio.
maxFiles number Using this parameter, you can choose the maximum number of files allowed to upload.
minFiles number Using this parameter you can choose the minimum number of files allowed to upload.
startUploadingWhenMaxFilesReached boolean Using this parameter, you can choose whether to start uploading automatically when maxFiles is hit.
supportEmail string Using this parameter, you can set the support email to display in case of the error.
uploadInBackground string Using this parameter, you can choose if Picker should start uploading immediately on file selection. Please note, that this feature can be enabled only if crop is disabled by setting disableTransformer: true.
videoResolution string Using this parameter, you can choose the resolution of the recorded video. Possible values are '320x240', '640x480' or '1280x720'.
viewType string Using this parameter, you can choose the default view type option for file browser. Possible values are 'grid' or 'list'.
accept array Using this parameter, you can choose the types of files that the user is allowed to upload. Possible values are presented on GitHub.
fromSources array Using this parameter, you can choose the list of services you would like to display to your users so they can upload files from. Possible values are presented on GitHub.

Examples:

fromSources array

Using fromSources array, you can configure a list of services you would like to display to your users so they can choose files from. Example below limits sources to local computer, Intagram, and Facebook only.

const client = filestack.init(YOUR_API_KEY);
const options = {
  fromSources: ["local_file_system","instagram","facebook"],
};

client.picker(options).open();

Please find the list of available sources presented below.
SOURCE DEFAULT DESCRIPTION
local_file_system yes This is your user's disk.
url yes Upload file directly from URL.
imagesearch yes Search for images in the File Picker.
facebook yes
instagram yes
googledrive yes
dropbox yes You will need your own OAuth2 application with Dropbox. You can read more about it in our tutorial.
unsplash no Search for free, high-quality images from the Unsplash community.
webcam no Uses device menu on mobile. Not currently supported in Safari and IE.
video no Uses device menu on mobile. Not currently supported in Safari and IE.
audio no Uses device menu on mobile. Not currently supported in Safari and IE.
box no
gmail no
googlephotos no
onedrive no
onedriveforbusiness no You will need your own OAuth2 application with OneDrive for Business. You can read more about it in our tutorial.
customsource no This is your S3 bucket as a source. You can find more about it here.

accept array

Using accept array you can specify the types of files that the user is allowed to choose. For example, if you want the user to select images, you can specify ["image/*"] and users would only be able to select images to upload. Similarly, you could specify ["application/pdf"] to only allow PDF documents to be selected.

const client = filestack.init(YOUR_API_KEY);
const options = {
  accept: ["image/*"],
};

client.picker(options).open();

There are multiple formats accepted. For example:

  • .pdf - any file extension
  • image/jpeg - any mime type commonly known by browsers
  • image/* - accept all types of images
  • video/* - accept all types of video files
  • audio/* - accept all types of audio files
  • application/* - accept all types of application files
  • text/* - accept all types of text files

Store Options

Picker Store Options interface can be used to control how and where your users’ files are stored. With Filestack, you can choose from multiple storage providers.

storeTo interface

If you choose not to use your own storage provider, we will upload files to default Filestack S3 bucket. If you choose to use your own S3 and you configured it in Filestack Developer Portal we will also use it by default.

If you would like to change that behavior and, for example, use a different storage provider, or upload files to a different path than the default / path you should use storeTo parameter of the Picker Options.

const client = filestack.init(YOUR_API_KEY);
const options = {
    storeTo: {
        location: 'azure',
        path: '/site_uploads/'
    }
};

client.picker(options).open();

Learn more about all Picker Store Options from our JavaScript SDK Reference.

workflowsinterface

Workflows allow you to wire up conditional logic and image processing to enforce business processes, automate ingest, and save valuable development time. Once you’ve configured a workflow, it can be called with a single reference in your upload code. Learn more about Workflows from our documentation and tutorial.

In order to trigger the workflow job for each upload in the File Picker, you need to attach your workflow ID to the storeTo options like this:

const client = filestack.init(YOUR_API_KEY);
const options = {
  storeTo: {
    workflows: [YOUR_WORKFLOW_ID]
  }
};
picker = client.picker(options);
picker.open();

Upload Options

Upload Options interface lets you control low-level details on how files from the local file system are uploaded. You can control timeout and retry settings as well as advanced configuration of Filestack’s Content Ingestion Network and Intelligent Ingestion.

You can also define onProgress and onRetry callbacks to improve the user experience of your application.

uploadConfig interface

For example, if you would like to change retry logic and timeout settings, you can do it like this:

const client = filestack.init(YOUR_API_KEY);
const options = {
    uploadConfig: {
        retry: 5,
        timeout: 60000
    }
};

client.picker(options).open();

Learn more about all Upload Options from our JavaScript SDK Reference.

Upload Tags

Upload Tags allows you to pass custom data (tags) with each file that is uploaded using File Picker. That data specified in the Picker code should have a format of key-value pair, and it will be returned in the exact same configuration in the upload response and in the Webhook .

In order to add tags, you need to specify the key-value or key-function pair in uploadConfig Picker option.

If pair key-function is provided function will be called with the current file parameter before upload. Function should return a string value that will be sent as value of tag.

const client = filestack.init(APIKEY);
const options = {
  uploadConfig: {
    	tags: {
          "foo": "bar",
          "foo2": (file) => "bar2_" + file.name
      }
    },
  fromSources: ["local_file_system","instagram","facebook"],
};
client.picker(options).open();

The example upload response with upload tags:

{
  "handle":"HANDLE",
  "url":"https://cdn.filestackcontent.com/HANDLE",
  "filename":"filename.jpg",
  "size":68772,
  "mimetype":"image/jpeg",
  "key":"HLcysRpSTcOQGVENECH9_filename.jpg",
  "container":"YOUR_BUCKET",
  "status":"Stored",
  "upload_tags":
        {
          "foo":"bar",
          "foo2":"bar2_file_name"
        }
  }

Please learn more about Upload Tags here.

Transformation Options

Transformation Options interface lets you control how users can manipulate images before they reach out to your destination storage.

transformations interface

Currently users can crop, circle and rotate images in the File Picker. You can control them by setting a boolean flag and decide whether any of them should be enabled or not. For example:

const client = filestack.init(YOUR_API_KEY);
const options = {
    transformations: {
        crop: false,
        circle: true,
        rotate: true
    }
};

client.picker(options).open();

Learn more about all Transformation Options from our JavaScript SDK Reference.

Callbacks

In order to give you the ability to interact with Picker and provide a seamless experience for your users, we provide the following list of callbacks. Most callbacks are part of PickerOptions interface. Some, like onProgress and onRetry, are part of the UploadOptions interface.

CALLBACK DESCRIPTION
onCancel Called when all uploads in a pick are canceled.
onClose Called when the UI is exited.
onFileSelected Called whenever user selects a file.
onFileUploadFailed Called when uploading a file fails.
onFileUploadFinished Called when a file is done uploading.
onFileUploadProgress Called during multi-part upload progress events. Local files only.
onFileUploadStarted Called when a file begins uploading.
onOpen Called when the UI is mounted.
onUploadDone Called when all files have been uploaded.
onUploadStarted Called when uploading starts (user initiates uploading).
UploadOptions / onProgress Callback for progress events.
UploadOptions / onRetry Callback for retry events.
acceptFn Provide your own accept function.

For example, if you would like to verify the size of the selected file before upload you can use onFileSelected callback as shown below:

const client = filestack.init(YOUR_API_KEY);

const options = {
    onFileSelected: file => {
        // If you throw any error in this function it will reject the file selection.
        // The error message will be displayed to the user as an alert.
        if (file.size > 1000 * 1000) {
            throw new Error('File too big, select something smaller than 1MB');
        }
    }
};

client.picker(options).open();
acceptFn - Providing this param will replace the default accept checking function with user provided one.

acceptFn - should return promise or throw error. Error message will be displayed to user as toast. Function is working alongside accept argument, so all mimetypes and extensions from accept will be added to input tag as accept argument.

  • file - filestack file object containing original browser file object
  • options - additional tools for checking mimetype of the file
    • accept - provided by accept
    • acceptMime - accept converted to mimeType
    • mimeFromMagicBytes - promise that calculate file type based on mimeType
    • mimeFromExtension - function that calculate file type based on file extension
accept: ['image/*'],
acceptFn: (file, options) => {
  return options.mimeFromMagicBytes(file.originalFile).then((res) => { // we can check mimetype from magic bytes
    //console.log(options.mimeFromExtension(file.originalFile.name)); // or check extension from filestack extensions database
  
    // throw new Error('Cannot accept that file') // we can throw exception to block file upload
    // return Promise.reject('Cannot accept that file'') // or reject a promise
    return Promise.resolve();
  });
},

Example of checking file extension:

accept: ['.png'],
acceptFn: (file, options) => {
  const mimeFromExtension = options.mimeFromExtension(file.originalFile.name);
  if(options.acceptMime.length && !options.acceptMime.includes(mimeFromExtension)) {
    return Promise.reject('Cannot accept that file')
  }
  return Promise.resolve()
},

Example of acceptFn callback usage for files uploaded from local_source, as well as, from cloud providers:

acceptFn: async (file, options) => {
      let mimeTest = ""

      // Local File system has the unique .originalFile key
      if (file.source === "local_file_system") {
        const magicMime = await options.mimeFromMagicBytes(file.originalFile)
        const extMime = await options.mimeFromExtension(file.originalFile.name)
        mimeTest = magicMime.indexOf("audio/") >= 0 ? magicMime : extMime
        // Use mimeType if it's set
      } else if (file.mimetype) {
        mimeTest = file.mimetype
        // Fall back to Filestack's built in extension detector
      } else {
        mimeTest = await options.mimeFromExtension(file.name)
      }

      if (mimeTest.indexOf("audio/") === -1) {
        return Promise.reject(
          'Please upload a valid audio file.'
        )
      }

      return Promise.resolve()
    },

If acceptFn is not explicitly provided than following check will take place

  • Determine mimetype

    • get mimeType from browser
    • if mimeType from browser not recognized than extensionToMime method is used
    • if found mimetype is not supported fallback to recognize from magicBytes using npm file-type is done to avoid browser or system incompatibility
    • if none recognized then application/octet-stream is set as mimetype
  • Accept procedure

    • when extension like .png is provided, we change it to mimetype using extensionToMime
    • compare it with determined mimetype
  • when pattern i.e. image/* is provided we compare it over determined mimetype, below list of supported global patterns

    • image/*
    • video/*
    • audio/*
    • application/*
    • text/*

Learn more about callbacks from our JavaScript SDK Reference.

Custom sources

With Custom Source functionality, you can add your own integration to the File Picker based either on a static list of files or a dynamic integration of your choice.

Documentation

Tutorial

Github repository

Security

In order to make sure that you have full control on who and when opens the Picker and uploads files you can leverage Filestack’s universal security policies mechanism.

To work with the Picker, your policy will need the following calls:

CALL DESCRIPTION
pick Ability to open Picker and pick files.
store Ability to store files in your storage destination.
runWorkflows Ability to run workflows after the file is uploaded.

Remember about expiry key which, while optional, is necessary to provide maximum security and to make your policies TTL reasonably short.

Example policy would look like this:

{
  "expiry": 1523595600,
  "call": ["pick","store","runWorkflows"],
}

Having both policy and signature, you can use them in the Picker Client like this:

const clientOptions = {
    security: {
        policy: "eyJleHBpcnkiOiAxNTQ2ODk5NDI4LCAiY2FsbCI6IFsicmVhZCIsICJzdGF0IiwgImNvbnZlcnQiLCAicGljayIsICJzdG9yZSJdfQ==",
        signature: "1fed86599156df046f925e0f773866654a4fc209b0b85b173b5d8088e898b685"
    }
}

const client = filestack.init(YOUR_API_KEY, clientOptions)
client.picker().open();

Learn more about Security and other Client Options from our JavaScript SDK Reference.