node package manager

filestack-js

Official web SDK for the Filestack API and content management system.



What's in the box?

Installation

npm install --save filestack-js

Usage

ES module:

import filestack from 'filestack-js';
 
const apikey = 'abc';
const client = filestack.init(apikey);

Script:

<script src="//static.filestackapi.com/v3/filestack-0.7.0.js"></script>
<script>
  const apikey = 'abc';
  const client = filestack.init(apikey);
</script>

Promises

This library requires an environment that implements the Promise object spec. If you target IE11 you will need to add a Promise polyfill to your page or application.

Polyfills we recommend:

Module (for bundling):

Script (for script tag):

Known Issues

Currently the picker requires support for third-party cookies. End users will need to accept third-party cookies to authenticate with cloud sources. We are actively working to change this.

API Reference

init(apikey, [security]) ⇒ object

Initializes the client.

Returns: object - Object containing client methods.
Params

  • apikey string - Filestack API key. Get a free key here.
  • [security] object - Read about security policies.
    • .policy string - Filestack security policy encoded in base64.
    • .signature string - HMAC-SHA256 signature for the security policy.

version ⇒ string

Gets current version.

Example

import filestack from 'filestack-js';
console.log(filestack.version);

client.getSecurity() ⇒ object

Get current security parameters.

Returns: object - Object containing current security parameters

client.setSecurity(security) ⇒ object

Set security parameters -- useful for changing policy on instantiated client.

Note: Does not currently work with pick. You will need to init a new client if you want to propagate new security parameters to the picker.

Returns: object - Object containing current session parameters
Params

  • security object - Read about security policies.
    • .policy string - Filestack security policy encoded in base64.
    • .signature string - HMAC-SHA256 signature for the security policy.

Example

client.setSecurity({ policy: 'policy', signature: 'signature' });

client.pick([options]) ⇒ Promise

Attaches and opens the picker UI in the current DOM.

Resolve: object - Object contains keys filesUploaded and filesFailed which are both arrays of file metadata.
Params

  • [options] object
    • .fromSources Array.<string> - Valid sources are:
      • local_file_system - Default
      • url - Default
      • imagesearch - Default
      • facebook - Default
      • instagram - Default
      • googledrive - Default
      • dropbox - Default
      • webcam - Desktop only. Not currently supported in Safari and IE.
      • evernote
      • flickr
      • box
      • github
      • gmail
      • picasa
      • onedrive
      • clouddrive
      • customsource - Configure this in your Filestack Dev Portal.
    • .accept string | Array.<string> - Restrict file types that are allowed to be picked. Formats accepted:
      • .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
    • .customSourceContainer string - Set the default container for your custom source.
    • .customSourcePath string - Set the default path for your custom source container.
    • .preferLinkOverStore boolean = false - For cloud sources whether to link or store files.
    • .lang string = "en" - Sets locale. Accepts: da, de, en, es, fr, it, ja, nl, pl, pt, ru, zh.
    • .minFiles number = 1 - Minimum number of files required to start uploading.
    • .maxFiles number = 1 - Maximum number of files allowed to upload.
    • .maxSize number - Restrict selected files to a maximum number of bytes. (e.g. 10 * 1024 * 1024 for 1MB limit).
    • .startUploadingWhenMaxFilesReached boolean = false - Whether to start uploading automatically when maxFiles is hit.
    • .hideWhenUploading boolean = false - Hide the picker UI once uploading begins.
    • .uploadInBackground boolean = true - Start uploading immediately on file selection.
    • .disableThumbnails boolean = false - Disables local image thumbnail previews in the summary screen.
    • .disableTransformer boolean = false - When true removes ability to edit images.
    • .transformations object - Specify transforms for images passed to the transformations UI.
      • .crop boolean | object = true - Enable crop.
        • .aspectRatio number - Maintain aspect ratio for crop selection. (e.g. 16/9 or 4/3)
        • .circle boolean = true - Enable circle crop. Disabled if aspectRatio is defined and not 1.
      • .minDimensions array - Minimum dimensions for picked image. Image will be upscaled if smaller. (e.g. [200, 300])
      • .maxDimensions array - Maximum dimensions for picked image. Image will be downscaled if smaller. (e.g. [200, 300])
      • .filters Array.<string> - Enable image filters. Pick from: sepia, monochrome. All enabled by default.
    • .storeTo object - Options for file storage.
      • .location string = "s3" - One of s3, gcs, rackspace, azure, dropbox.
      • .region string - Valid S3 region for the selected S3 bucket. S3 only.
      • .container string
      • .path string
      • .access string - One of public or private.
    • .onFileSelected onFileSelected - Called whenever user selects a file.
    • .onFileUploadStarted onFileUploadStarted - Called when a file begins uploading.
    • .onFileUploadProgress onFileUploadProgress - Called during multi-part upload progress events. Local files only.
    • .onFileUploadFinished onFileUploadFinished - Called when a file is done uploading.
    • .onFileUploadFailed onFileUploadFailed - Called when uploading a file fails.
    • .onClose function - Called when the UI is exited.

Example

client.pick({
  maxFiles: 20,
  fromSources: ['local_file_system', 'facebook'],
}).then(res => console.log(res));

onFileSelected : function

Params

  • file object - File metadata.

Example

// Using to veto file selection 
// 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. 
onFileSelected(file) {
  if (file.size > 1000 * 1000) {
    throw new Error('File too big, select something smaller than 1MB');
  }
}
 
// Using to change selected file name 
onFileSelected(file) {
  file.name = 'foo';
  // It's important to return altered file by the end of this function. 
  return file;
}

onFileUploadStarted : function

Params

  • file object - File metadata.

onFileUploadFinished : function

Params

  • file object - File metadata.

onFileUploadFailed : function

Params

  • file object - File metadata.
  • error error - Error instance for this upload.

onFileUploadProgress : function

Params

  • file object - File metadata.
  • event object - Progress event.
    • .totalPercent number - Percent of file uploaded.
    • .totalBytes number - Total number of bytes uploaded for this file.

client.storeURL(url, [options]) ⇒ Promise

Interface to the Filestack Store API. Used for storing from a URL.

Resolve: object - Metadata of stored file.
Reject: error - A Superagent error object.
Params

  • url string - Valid URL to a file.
  • [options] object
    • .filename string
    • .location string = "s3" - One of s3, gcs, rackspace, azure, dropbox.
    • .mimetype string
    • .path string
    • .container string
    • .region string - Valid S3 region for the selected container (S3 only).
    • .access string - One of public or private.

Example

client
  .storeURL('https://d1wtqaffaaj63z.cloudfront.net/images/NY_199_E_of_Hammertown_2014.jpg')
  .then(res => console.log(res));

client.retrieve(handle, [options]) ⇒ Promise

Interface to the Filestack Retrieve API. Used for accessing files via Filestack handles.

Resolve: object - Metadata of stored file or stored file, depending on metadata / head option.
Reject: error - A Superagent error object.
Params

  • handle string - Valid Filestack handle.
  • [options] object
    • .metadata boolean - return json of file metadata
    • .head boolean - perform a 'head' request instead of a 'get'
    • .dl boolean - X-File-Name will be returned
    • .extension string - add extension to handle

Example

client
  .retrieve('DCL5K46FS3OIxb5iuKby')
  .then((blob) => {
     var urlCreator = window.URL || window.webkitURL;
     var imageUrl = urlCreator.createObjectURL(blob);
     document.querySelector('#myImage').src = imageUrl;
  })
  .catch((err) => {
     console.log(err);
  }));

client.remove(handle) ⇒ Promise

Interface to the Filestack Remove API. Used for removing files, requires security to be enabled.

Resolve: object - Result of remove.
Reject: error - A Superagent error object.
Params

  • handle string - Valid Filestack handle.

Example

client
  .remove('DCL5K46FS3OIxb5iuKby')
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  }));

client.metadata(handle, [options]) ⇒ Promise

Interface to the Filestack Metadata API. Used for retrieving detailed data of stored files.

Resolve: object - Result of metadata.
Reject: error - A Superagent error object.
Params

  • handle string - Valid Filestack handle.
  • [options] object
    • .size boolean
    • .mimetype boolean
    • .filename boolean
    • .width boolean
    • .height boolean
    • .uploaded boolean
    • .writeable boolean
    • .cloud boolean
    • .sourceUrl boolean
    • .md1 boolean
    • .sha1 boolean
    • .sha224 boolean
    • .sha256 boolean
    • .sha384 boolean
    • .sha512 boolean
    • .location boolean
    • .path boolean
    • .container boolean
    • .exif boolean

Example

client
  .metadata('DCL5K46FS3OIxb5iuKby')
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  }));

client.transform(url, options) ⇒ string

Interface to the Filestack transformation engine.

Returns: string - A new URL that points to the transformed resource.
Params

  • url string - Valid URL to an image.
  • options transformOptions - Transformations are applied in the order specified by this object.

Example

const transformedUrl = client.transform(url, {
  crop: {
    dim: {
      x: 0,
      y: 50,
      width: 300,
      height: 300,
    },
  },
  vignette: {
    blurmode: 'gaussian',
    amount: 50,
  },
  flip: true,
};
 
// optionally store the new URL 
client.storeURL(transformedUrl).then(res => console.log(res));

transformOptions : object

Params

  • crop object - Crop options.
    • .dim object - Crop dimensions.
      • .x number
      • .y number
      • .width number
      • .height number
  • resize object - Resize options. At least one option is required.
    • .width number
    • .height number
    • .fit string - One of clip, crop, scale, max.
    • .align string - One of center, top, bottom, left, right, faces, or align pair like ['top', 'left'].
  • rotate object - Rotate options. At least one option is required.
    • .deg number | string - Can be number in range 0-359 or exif.
    • .exif boolean
    • .background string
  • flip boolean - Flip image
  • flop boolean - Flop image
  • roundedCorners object - Rounded corners options.
    • .radius number | string - Can be number in range 1-10000 or max.
    • .blur number
    • .background string
  • vignette object - Vignette options.
    • .amount number
    • .blurmode string - One of linear or gaussian.
    • .background string
  • polaroid object - Polaroid options.
    • .color string
    • .rotate number
    • .background string
  • tornEdges object - Torn edges options.
    • .spread Array.<number> - Range format [10, 50].
    • .background string
  • shadow object - Shadow options.
    • .blur number
    • .opacity number
    • .vector Array.<number> - Range format [25, 25].
    • .color string
    • .background string
  • circle object - Circle options.
    • .background string
  • border object - Border options.
    • .width number
    • .color number
    • .background number
  • monochrome boolean - Monochrome.
  • sepia object - Sepia.
    • .tone number

client.upload(file, [uploadOptions], [storeOptions], [token]) ⇒ Promise

Initiates a direct-to-S3 multi-part upload. Uses Filestack S3 by default. Read how to configure your own S3 buckets here.

Resolve: object - Metadata of uploaded file.
Reject: error - An Error object depending on where the flow halted.
Params

  • file Blob - must be a valid File or Blob.
  • [uploadOptions] object
    • [.partSize] number = 6 * 1024 * 1024 - Size of each uploaded part.
    • [.concurrency] number = 5 - Max number of concurrent parts uploading.
    • [.retry] number = 10 - Number of times to retry a failed part of the flow.
    • [.progressInterval] number = 1000 - Frequency (in milliseconds) at which progress events are dispatched.
    • [.onProgress] progressCallback - Called regularly to give progress updates.
    • [.onRetry] retryCallback - Called when a retry is initiated.
  • [storeOptions] object - Configure where the file is stored.
    • [.filename] string - Define a custom filename for the Blob/File being uploaded.
    • [.location] string = "s3" - Valid options are: s3, gcs, dropbox, azure, rackspace.
    • [.region] string - Valid S3 region for the selected container (S3 only).
    • [.container] string - Name of the storage container.
    • [.path] string - Path where the file will be stored. A trailing slash will put the file in that folder path.
    • [.access] string - Valid options are private or public.
  • [token] object - A control token that can be used to call cancel(), pause(), and resume().

Example

const token = {};
const onRetry = (obj) => {
  console.log(`Retrying ${obj.location} for ${obj.filename}. Attempt ${obj.attempt} of 10.`);
};
 
client.upload(file, { onRetry }, { filename: 'foobar.jpg' }, token)
  .then(res => console.log(res));
 
token.pause();  // Pause flow 
token.resume(); // Resume flow 
token.cancel(); // Cancel flow (rejects) 

progressCallback : function

Params

  • event object - Progress event.
    • .totalPercent number - Percent of total file upload progress.
    • .totalBytes number - Total number of bytes uploaded thus far across all parts.

retryCallback : function

Params

  • retry object - Retry information object.
    • .location string - Which part of the flow is being retried.
    • .parts Array.<object> - Array of current parts at this point in the flow.
    • .filename string - Name of the file being retried.
    • .attempt number - Current attempt.

© 2017 Filestack.