node package manager

filestack-js

filestack-js

Official browser client to the Filestack API's. Available via NPM and CDN script.

Filestack documentation can be found here: https://filestack.com/docs/

Installation

npm install --save filestack-js

Usage

Via ES6 modules:

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

Via script tag:

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

API Reference

filestack~version ⇒ string

Gets current version.

Kind: inner property of filestack
Example

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

filestack~init(apikey, [security]) ⇒ object

Initializes the client.

Kind: inner method of filestack
Returns: object - Object containing the available methods documented below.
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.

client.getSecurity() ⇒ object

Get current security parameters.

Kind: static method of init
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 re-init the client if you want to propagate new security parameters to the picker.

Kind: static method of init
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

Opens the picker UI.

Kind: static method of init
Fulfil: 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
      • imagesearch - Default
      • facebook - Default
      • instagram - Default
      • googledrive - Default
      • dropbox - Default
      • evernote
      • flickr
      • box
      • github
      • gmail
      • picasa
      • onedrive
      • clouddrive
    • .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/* <- special mime type accepting all types of images
      • video/* <- special mime type accepting all types of video files
      • audio/* <- special mime type accepting all types of audio files
    • .preferLinkOverStore boolean = false - For cloud sources whether to link or store files.
    • .lang string = "en" - Sets locale. Accepts: da, de, en, es, fr, it, 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.
    • .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.
    • .disableTransformer boolean = false - When true removes ability to edit images with transformer UI.
    • .transformOptions object - Options to be passed to the transformer UI.
      • .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])
      • .transformations object - Enable and set options for various transformations.
        • .crop boolean | object - Enable crop.
          • .aspectRatio number - Maintain aspect ratio for crop selection. (e.g. 16/9 or 4/3)
        • .rotate boolean - Enable rotate.
        • .circle boolean - Enable circle.
        • .monochrome boolean - Enable monochrome.
        • .sepia boolean - Enable sepia.
    • .storeTo object - Options for file storage.
      • .location string = "s3" - One of s3, gcs, rackspace, azure, dropbox.
      • [.region] string - Valid S3 region for the selected container (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.
    • .onFileUploadFinished onFileUploadFinished - Called when a file is done uploading.
    • .onFileUploadFailed onFileUploadFailed - Called when uploading a file fails.

Example

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

client.pick~onFileSelected : function

Kind: inner typedef of pick

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

client.pick~onFileUploadStarted : function

Kind: inner typedef of pick

Params

  • file object - File metadata.

client.pick~onFileUploadFinished : function

Kind: inner typedef of pick

Params

  • file object - File metadata.

client.pick~onFileUploadFailed : function

Kind: inner typedef of pick

Params

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

client.pick~onFileUploadProgress : function

Kind: inner typedef of pick

Params

  • file object - File metadata.
  • event object - Progress event.
    • .totalProgressPercent number - Percent of total upload.
    • .progressTotal number - Total number of bytes uploaded thus far across all parts.
    • .part number - Part #.
    • .loaded number - Amount of data in this part that has been uploaded.
    • .byteLength number - Total number of bytes in this part.

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

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

Kind: static method of init
Fulfil: 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.

Kind: static method of init
Fulfil: 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.

Kind: static method of init
Fulfil: 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.

Kind: static method of init
Fulfil: 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.

Kind: static method of init
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));

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

Initiates a multi-part upload flow.

Kind: static method of init
Fulfil: object - Metadata of uploaded file.
Reject: error - An error object depending on where the flow halted.
Params

  • file File - must be a valid File.
  • [uploadOptions] object
    • [.partSize] number = 5 * 1024 * 1024 - Size of each uploaded part.
    • [.maxConcurrentUploads] number = 5 - Max number of concurrent uploads.
    • [.retryOptions] object - params for retry settings
      • [.retries] number = 10 - max number of retries
      • [.factor] number = 2 - the exponential factor to use
      • [.minTimeout] number = 1 * 1000 - ms before starting first retry
      • [.maxTimeout] number = 60 * 1000 - max ms between two retries
    • [.onStart] function - Called when the flow begins (before Filestack handshake request is made).
    • [.onUploadStart] function - Called when an upload begins (after S3 request is made).
    • [.onProgress] progressCallback - Called on progress event.
    • [.onRetry] retryCallback - Called if upload fails and retry is occurring
    • [.onUploadComplete] function - Called when an upload is completing (before final completion request).
  • [storeOptions] object - Configure where the file is stored.
    • .location string - Valid options are: s3, gcs, dropbox, azure, rackspace.
    • .container string - Name of the storage container.
    • [.region] string - Valid S3 region for the selected container (S3 only).
    • .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.

Example

client.upload(file).then(res => console.log(res));

filestack~TransformOptions : object

Kind: inner typedef of filestack
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

filestack~progressCallback : function

Kind: inner typedef of filestack
Params

  • event object - Progress event.
    • .totalProgressPercent number - Percent of total upload.
    • .progressTotal number - Total number of bytes uploaded thus far across all parts.
    • .part number - Part #.
    • .loaded number - Amount of data in this part that has been uploaded.
    • .byteLength number - Total number of bytes in this part.

filestack~retryCallback : function

Kind: inner typedef of filestack
Params

  • attempt number - Which attempt the upload is currently on.
  • nextAttempt number - ms before the attempt will start

© 2017 Filestack.