Options
All
  • Public
  • Public/Protected
  • All
Menu


Javascript SDK for the Filestack API and content management system.



What's in the box?

  • A multi-part uploader powered on the backend by the Filestack CIN.
  • An interface to the Filestack Processing Engine for transforming assets via URLs.
  • The Filestack Picker - an upload widget for the web that integrates over a dozen cloud providers and provides pre-upload image editing.

Installation

npm install filestack-js

Usage

Browsers

ES module:

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

UMD module:

<script src="//static.filestackapi.com/filestack-js/1.x.x/filestack.min.js"></script>
<script>
  const client = filestack.init('apikey');
</script>

Node

CommonJS module:

const client = require('filestack-js').init('apikey');

Module Overview

The package.json specifies two separate modules:

  • main for the CommonJS module (intended for Node runtimes)
  • browser for the pre-bundled ES module (intended for browser runtimes)

Node projects which depend on filestack-js will follow the main field in package.json. When building for the browser, newer tools (like Webpack, Rollup, and Parcel) follow the browser field, which will resolve to the pre-bundled ES module. Both modules follow the same API, but some methods behave differently based on their runtime. For example, client.upload treats the file argument as a file path in Node but in browsers it assumes a Blob object.

The pre-bundled browser module is also available in UMD format. This is useful if you are using script tags on a web page instead of bundling your application. It can be retrieved from both the Filestack CDN and the unpkg CDN:

Live examples (JSFiddle)

Upload image
Open picker
Open picker in inline mode
Crop images
Multiple drop panes
Preview
Import using RequireJS
Retrieve image data
Transform image
Custom Picker CSS
Assign file to user

Examples can be run locally with:

npm run examples

Picker Quick Start

If you are here to use the picker widget, it can be initialized from the Filestack client by calling client.picker(options). Options for the picker are documented here.

The picker instance returned from client.picker can be controlled with a few methods:

  • open - Create the application and mount it into the DOM based on the displayMode.
  • close - Close the application and remove its resources from the DOM.
  • crop(files) - Create the application, mount it, and pre-select the passed files for cropping.
  • cancel - Cancel all uploads controlled by this instance.

Please see our examples above to learn more about customizing the picker for your use case.

API Documentation

https://filestack.github.io/filestack-js/

Promises

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

Polyfills we recommend:

Module (for bundling):

Script (for script tag):

Development

Most tests in this library are expected to interface with actual backend services. Because we like to run tests during development, these services are mocked during unit testing.

All tests are using Mocha. Browser tests are run with Karma.

To run units:

npm test

To run integration tests:

npm run test:integration

Integration tests require a .env file in the root of your project with the following fields:

BROWSERSTACK_USERNAME=
BROWSERSTACK_ACCESS_KEY=
TEST_APIKEY=
TEST_CLOUD_APIKEY=
TEST_INTELLIGENT_APIKEY=
TEST_SECURE_APIKEY=
TEST_SIGNATURE=
TEST_POLICY=
TEST_FILELINK=
TEST_SECURE_FILELINK=

You will need to acquire this data from a Filestack developer if you plan on running the integration suite.

Contributing

We follow the conventional commits specification to ensure consistent commit messages and changelog formatting.

Index

Enumerations

Classes

Interfaces

Variables

Functions

Object literals

Variables

Private Const MIN_CHUNK_SIZE

MIN_CHUNK_SIZE: number = 32 * 1024

Private Const PICKER_KEY

PICKER_KEY: "__fs_picker_token" = "__fs_picker_token"

Private Const PICKER_VERSION

PICKER_VERSION: "1.2.3" = "1.2.3"

Private Let config

config: Config

Private Const request

request: agent.SuperAgentStatic = agent

Private Const vAlignment

vAlignment: Enums = t.enums.of('top left right bottom center')

Private Const vBlurMode

vBlurMode: Enums = t.enums.of('linear gaussian')

Private Const vColor

vColor: Irreducible<string> = t.String

Private Const vColorspace

vColorspace: Enums = t.enums.of('RGB CMYK Input')

Private Const vCropfaces

vCropfaces: Enums = t.enums.of('thumb crop fill')

Private Const vFit

vFit: Enums = t.enums.of('clip crop scale max')

Private Const vRotate

vRotate: Union<number> = t.union([t.enums.of('exif'), vRange(1, 359) ])

Private Const vShapeType

vShapeType: Enums = t.enums.of('rect oval')

Private Const validationSchema

validationSchema: any[] = [{name: 'flip',validator: t.Boolean,},{name: 'compress',validator: t.Boolean,}, {name: 'flop',validator: t.Boolean,}, {name: 'tags',validator: t.Boolean,}, {name: 'sfw',validator: t.Boolean,}, {name: 'monochrome',validator: t.Boolean,}, {name: 'enhance',validator: t.Boolean,}, {name: 'redeye',validator: t.Boolean,}, {name: 'negative',validator: t.Boolean,}, {name: 'resize',props: {width: t.Integer,height: t.Integer,fit: vFit,align: vAlignment,},}, {name: 'crop',props: {dim: t.tuple([t.Integer, t.Integer, t.Integer, t.Integer]),},}, {name: 'resize',props: {width: t.Integer,height: t.Integer,fit: vFit,align: vAlignment,},}, {name: 'rotate',props: {deg: vRotate,colour: vColor,background: vColor,},}, {name: 'rounded_corners',canBeBoolean: true,props: {radius: vRange(1, 10000),blur: vRange(0, 20),background: vColor,},}, {name: 'vignette',props: {amount: vRange(0, 100),blurmode: vBlurMode,background: vColor,},}, {name: 'polaroid',canBeBoolean: true,props: {color: vColor,rotate: vRotate,background: vColor,},}, {name: 'torn_edges',canBeBoolean: true,props: {spread: t.tuple([vRange(1, 10000), vRange(1, 10000)]),background: vColor,},}, {name: 'shadow',canBeBoolean: true,props: {blur: vRange(0, 20),opacity: vRange(0, 100),vector: t.tuple([vRange(-1000, 1000), vRange(-1000, 1000)]),color: vColor,background: vColor,},}, {name: 'circle',canBeBoolean: true,props: {background: vColor,},}, {name: 'border',canBeBoolean: true,props: {width: vRange(1, 1000),color: vColor,background: vColor,},}, {name: 'sharpen',canBeBoolean: true,props: {amount: vRange(1, 20),},}, {name: 'blackwhite',canBeBoolean: true,props: {threshold: vRange(0, 100),},}, {name: 'blur',canBeBoolean: true,props: [{name: 'amount',validator: vRange(2, 20),required: true,}],}, {name: 'sepia',canBeBoolean: true,props: {tone: vRange(1, 100),},}, {name: 'pixelate',canBeBoolean: true,props: [{name: 'amount',validator: vRange(2, 100),required: true,}],}, {name: 'oil_paint',canBeBoolean: true,props: {amount: vRange(1, 10),},}, {name: 'modulate',canBeBoolean: true,props: {brightness: vRange(0, 10000),hue: vRange(0, 359),saturation: vRange(0, 10000),},}, {name: 'partial_pixelate',props: {amount: vRange(2, 100),blur: vRange(0, 20),type: vShapeType,objects: t.list(t.tuple([t.Integer, t.Integer, t.Integer, t.Integer])),},}, {name: 'partial_blur',props: {amount: vRange(2, 100),blur: vRange(0, 20),type: vShapeType,objects: t.list(t.tuple([t.Integer, t.Integer, t.Integer, t.Integer])),},}, {name: 'collage',props: {files: t.list(t.String),margin: t.Integer,width: t.Integer,height: t.Integer,color: vColor,fit: vFit,autorotate: t.Boolean,},}, {name: 'upscale',canBeBoolean: true,props: {upscale: t.Boolean,noise: t.enums.of('none low medium high'),style: t.enums.of('artwork photo'),},}, {name: 'ascii',canBeBoolean: true,props: {background: vColor,foreground: vColor,colored: t.Boolean,size: vRange(10, 100),reverse: t.Boolean,},}, {name: 'quality',props: {value: t.Number,},}, {name: 'security',props: {policy: t.String,signature: t.String,},}, {name: 'cache',canBeBoolean: true,props: {cache: t.Boolean,expiry: t.Integer,},}, {name: 'output',props: {format: t.String,colorspace: vColorspace,strip: t.Boolean,quality: vRange(1, 100),page: vRange(1, 10000),compress: t.Boolean,density: vRange(1, 500),background: vColor,secure: t.Boolean,docinfo: t.Boolean,pageformat: t.enums.of('a3 A3 a4 A4 a5 A5 b4 B4 b5 B5 letter legal tabloid'),pageorientation: t.enums.of('portrait landscape'),},}, {name: 'crop_faces',props: {mode: vCropfaces,width: t.Integer,height: t.Integer,faces: vNumberOrAll(),buffer: t.Integer,},}, {name: 'detect_faces',canBeBoolean: true,props: {minsize: vFloatOrRange(0, 10000),maxsize: vFloatOrRange(0, 10000),color: vColor,export: t.Boolean,},}, {name: 'pixelate_faces',props: {faces: vNumberOrAll(),minsize: vFloatOrRange(0, 10000),maxsize: vFloatOrRange(0, 10000),buffer: vRange(0, 1000),amount: vRange(2, 100),blur: vRange(0, 20),type: vShapeType,},}, {name: 'blur_faces',props: {faces: vNumberOrAll(),minsize: vFloatOrRange(0, 10000),maxsize: vFloatOrRange(0, 10000),buffer: vRange(0, 1000),amount: vRange(2, 100),blur: vRange(0, 20),type: vShapeType,},}, {name: 'video_convert',props: {preset: t.enums.of('h264 h264.hi webm webm.hi ogg ogg.hi hls.variant mp3 oga m4a aac hls.variant.audio'),force: t.Boolean,title: t.String,extname: t.String,filename: t.String,location: t.enums.of('S3 s3 azure gcs rackspace dropbox'),path: t.String,access: t.enums.of('private public'),container: t.String,audio_bitrate: vRange(0, 999),video_bitrate: vRange(1, 5000),audio_sample_rate: vRange(0, 99999),audio_channels: vRange(1, 12),upscale: t.Boolean,aspect_mode: t.enums.of('preserve constrain letterbox pad crop'),clip_length: t.String,clip_offset: t.String,width: t.Number,height: t.Number,two_pass: t.Boolean,fps: vRange(1, 300),keyframe_interval: vRange(1, 300),watermark_url: t.String,watermark_top: t.Number,watermark_bottom: t.Number,watermark_right: t.Number,watermark_left: t.Number,watermark_width: t.Number,watermark_height: t.Number,},},]

Const version

version: "@{VERSION}" = "@{VERSION}"

filestack-js version. Interpolated at build time.

Functions

Private Const applySchemaValidators

  • applySchemaValidators(validators: any, canBeBoolean?: boolean, maybe?: boolean): any
  • Parameters

    • validators: any
    • Default value canBeBoolean: boolean = false
    • Default value maybe: boolean = false

    Returns any

Private Const arrayToString

  • arrayToString(arr: any[]): string

Private Const b64toBlob

  • b64toBlob(b64Data: string, sliceSize?: number): Blob
  • Convert encoded base64 string or dataURI to blob

    Parameters

    • b64Data: string
    • Default value sliceSize: number = 512

      Byte quantity to split data into

    Returns Blob

Private Const calcMD5

  • calcMD5(data: any): string
  • Calculates a MD5 checksum for passed buffer

    Parameters

    • data: any

      Data to be hashed

    Returns string

    base64 encoded MD5 hash

Private Const checkOptions

  • checkOptions(name: string, allowed: any, options?: any): __type
  • Check config options

    Parameters

    • name: string
    • allowed: any
    • Default value options: any = {}

    Returns __type

Const closeFile

  • closeFile(): any

Private Const commitPart

Private Const complete

  • complete(etags: string, __namedParameters: object): Promise<any>
  • Completes upload flow (/multipart/complete)

    Parameters

    • etags: string

      An array of etags from each S3 part

    • __namedParameters: object

    Returns Promise<any>

Private Const flowControl

  • flowControl(ctx: Context, func: any): (Anonymous function)
  • Returns a Promise based on the flow state If the flow is paused it will return a Promise that resolves when resumed If the flow failed it will resolve harmlessly

    Parameters

    • ctx: Context
    • func: any

      function that returns a Promise

    Returns (Anonymous function)

Private Const formatETags

  • formatETags(etags: any): string
  • Convert array of Etags into format for /multipart/complete call

    Parameters

    • etags: any

      Array of Etag strings

    Returns string

Private Const gc

Private Const getFile

  • getFile(fileOrString: any): Promise<Blob>
  • getFile(inputFile: string | Buffer): Promise<FileObj>
  • Get a Blob from a File or string. Given a file path, returns a file object

    Parameters

    • fileOrString: any

    Returns Promise<Blob>

  • Get a Blob from a File or string. Given a file path, returns a file object

    Parameters

    • inputFile: string | Buffer

      A valid path to a file on your filesystem or buffer.

    Returns Promise<FileObj>

Private Const getFormData

  • getFormData(fields: any, __namedParameters: object): __type
  • Generates multi-part fields for all requests

    Parameters

    • fields: any

      Object containing form data keys

    • __namedParameters: object
      • store: any

    Returns __type

Private Const getHost

  • getHost(host?: string): string

Private Const getLocationURL

  • getLocationURL(url: string): string

Const getMimetype

  • getMimetype(buffer: any): any

Private Const getName

  • getName(file: any, cfg: any): any

Private Const getPart

  • Reads a slice of a file based on the current part. Given a file with a valid descriptor this will return a part object The part object represents a chunk of the file

    Parameters

    Returns Promise<object>

  • Reads a slice of a file based on the current part. Given a file with a valid descriptor this will return a part object The part object represents a chunk of the file

    Parameters

    Returns Promise<PartObj>

Private Const getProgress

  • getProgress(__namedParameters: object): object

Private Const getRange

  • getRange(__namedParameters: object, partNumber: number): object

Private Const getS3PartData

  • getS3PartData(part: PartObj, __namedParameters: object): Promise<any>

Const getSecurity

  • getSecurity(): void
  • getSecurity(policyOptions: SecurityOptions, appSecret: string): Security
  • getSecurity is disabled for browsers. Returns Filestack base64 policy and HMAC-SHA256 signature

    Example

    import * as filestack from 'filestack-js';
    
    const jsonPolicy = { 'expiry': 253381964415 };
    const security = filestack.getSecurity(jsonPolicy, '<YOUR_APP_SECRET>');
    

    Returns void

  • getSecurity is disabled for browsers. Returns Filestack base64 policy and HMAC-SHA256 signature

    Example

    import * as filestack from 'filestack-js';
    
    const jsonPolicy = { 'expiry': 253381964415 };
    const security = filestack.getSecurity(jsonPolicy, '<YOUR_APP_SECRET>');
    

    Parameters

    • policyOptions: SecurityOptions
    • appSecret: string

    Returns Security

Private Const getUrl

  • getUrl(session: Session, handle: string, opts?: any, security?: Security): string

Const init

Private Const isBlob

  • isBlob(blob: any): boolean

Private Const isFile

  • isFile(file: any): boolean

Private Const makePart

Private Const metadata

Private Const optionToString

  • optionToString(key: string, values: any): string
  • Flatten transformation option to string

    Parameters

    • key: string

      option key

    • values: any

      option params

    Returns string

Private Const percentOfFile

  • percentOfFile(bytes: number, file: FileObj): number

Private Const picker

Private Const preview

Private Const range

  • range(start: number, stop: number, step?: number): any[]
  • Parameters

    • start: number
    • stop: number
    • Default value step: number = 1

    Returns any[]

Private Const readFile

  • readFile(file: any): Promise<Object>
  • Reads file as ArrayBuffer using HTML5 FileReader implementation

    Parameters

    • file: any

      Valid File instance

    Returns Promise<Object>

Private Const remove

  • remove(session: Session, handle?: string, skipStorage?: boolean, security?: Security): Promise<any>
  • Remove given file

    Parameters

    • session: Session
    • Optional handle: string
    • Optional skipStorage: boolean
    • Optional security: Security

    Returns Promise<any>

Private Const removeEmpty

  • removeEmpty(obj: any): any

Private Const requestWithSource

  • requestWithSource(method: string, url: string): CustomReq

Private Const resolveCdnUrl

  • resolveCdnUrl(session: Session, handle: string): string
  • Resolve cdn url based on handle type

    Parameters

    • session: Session

      session object

    • handle: string

      file handle (hash, src://alias, url)

    Returns string

Private Const retrieve

Private Const sliceFile

  • sliceFile(ctx: Context, partNumber: number): any

Private Const slicePartIntoChunks

  • slicePartIntoChunks(part: PartObj, size: number): any[]

Private Const start

  • start(__namedParameters: object): Promise<any>

Private Const storeURL

  • storeURL(session: any, url?: string, opts?: StoreOptions, token?: any, security?: Security): Promise<__type>

Private Const sumBytes

  • sumBytes(bytes: number[]): number
  • Helpers to calculate total progress of file upload in bytes and percent

    Parameters

    • bytes: number[]

    Returns number

Private Const throat

  • throat(size: number, fn: any): (Anonymous function)

Private Const throttle

  • throttle(fn: any, interval: number, callFirst?: boolean): (Anonymous function)
  • Parameters

    • fn: any
    • interval: number
    • Optional callFirst: boolean

    Returns (Anonymous function)

Private Const toSnakeCase

  • toSnakeCase(original: object): object
  • Parameters

    • original: object
      • [index: string]: any

    Returns object

    • [index: string]: any

Private Const toTcombSchema

Private Const transform

  • Creates filestack transform url. Transform params can be provided in camelCase or snakeCase style

    Parameters

    Returns string

Private Const upload

  • User facing method to upload a single file

    Parameters

    • session: Session

      Session object that contains apikey

    • fileOrString: any
    • Default value options: UploadOptions = {}

      Configures the uploader

    • Default value storeOptions: StoreOptions = {}

      Storage options for the backend

    • Default value token: any = {}

      Control token

    • Optional security: Security

    Returns Promise<any>

Private Const uploadChunk

  • uploadChunk(chunk: any, ctx: Context): Promise<any>

Private Const uploadFile

  • uploadFile(ctx: Context, token: any): Promise<any>

Private Const uploadPart

Private Const uploadToS3

  • uploadToS3(part: ArrayBuffer, params: any, onProgress: any, cfg: UploadConfig): Promise<any>
  • Uploads bytes directly to S3 with HTTP PUT

    Parameters

    • part: ArrayBuffer

      ArrayBuffer with part data

    • params: any

      Params for this part returned by getS3PartData response

    • onProgress: any

      A function to be called on progress event for this part

    • cfg: UploadConfig

    Returns Promise<any>

Private Const vFloat

  • vFloat(): Refinement<number>

Private Const vFloatOrRange

  • vFloatOrRange(start: number, end: number): Union<number>

Private Const vNumberOrAll

  • vNumberOrAll(): Union<number>

Private Const vRange

  • vRange(start: number, end: number): Refinement<number>

Object literals

Private Const statuses

statuses: object

DONE

DONE: Status = Status.DONE

FAILED

FAILED: Status = Status.FAILED

INIT

INIT: Status = Status.INIT

PAUSED

PAUSED: Status = Status.PAUSED

RUNNING

RUNNING: Status = Status.RUNNING