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.10.1.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 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):
API Reference
- filestack
- ~init(apikey, [security], [cname]) ⇒
object
- .getSecurity() ⇒
object
- .setSecurity(security) ⇒
object
- .logout() ⇒
Promise
- .metadata(handle, [options]) ⇒
Promise
- .pick([options]) ⇒
Promise
- .cropFiles(filesOrUrls, [pickOptions]) ⇒
Promise
- .makeDropPane(paneOptions, [pickOptions])
- .preview(handle, [options])
- .remove(handle) ⇒
Promise
- .retrieve(handle, [options]) ⇒
Promise
- .storeURL(url, [options]) ⇒
Promise
- .transform(url, options) ⇒
string
- .upload(file, [uploadOptions], [storeOptions], [token]) ⇒
Promise
- version ⇒
string
init(apikey, [security], [cname]) ⇒ 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.
- [cname]
string
- Custom domain to use for all URLs. This requires the custom CNAME feature on your Filestack app.
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.logout() ⇒ Promise
Logs out all current cloud sessions.
Returns: Promise
- Resolves/rejects when the request succeeds/fails.
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 objects.
Params
- [options]
object
- .fromSources
Array.<string>
- Valid sources are:
local_file_system
- Defaulturl
- Defaultimagesearch
- Defaultfacebook
- Defaultinstagram
- Defaultgoogledrive
- Defaultdropbox
- Defaultwebcam
- Desktop only. Not currently supported in Safari and IE.video
- Desktop only. Not currently supported in Safari and IE.audio
- Desktop only. Not currently supported in Safari and IE.evernote
flickr
box
github
gmail
picasa
onedrive
onedriveforbusiness
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 extensionimage/jpeg
<- any mime type commonly known by browsersimage/*
<- accept all types of imagesvideo/*
<- accept all types of video filesaudio/*
<- accept all types of audio filesapplication/*
<- accept all types of application filestext/*
<- 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. - .concurrency
number
= 4
- Max number of files to upload concurrently. - .preferLinkOverStore
boolean
= false
- For cloud sources whether to link or store files. - .lang
string
= "en"
- Sets locale. Accepts: da
, de
, en
, es
, fr
, he
, it
, ja
, ko
, nl
, no
, pl
, pt
, sv
, ru
, vi
, 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 10MB 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. - .disableStorageKey
boolean
= false
- When true removes the hash prefix on stored files. - .disableTransformer
boolean
= false
- When true removes ability to edit images. - .disableThumbnails
boolean
= false
- Disables local image thumbnail previews in the summary screen. - .videoResolution
string
= "640x480"
- Sets the resolution of recorded video. One of "320x240", "640x480" or "1280x720". - .transformations
object
- Specify options for images passed to the crop UI.
- .crop
boolean
| object
= true
- Enable crop.
- .aspectRatio
number
- Maintain aspect ratio for crop selection. (e.g. 16/9, 800/600). - .force
boolean
- Force all images to be cropped before uploading.
- .circle
boolean
= true
- Enable circle crop. Disabled if crop.aspectRatio
is defined and not 1. Converts to PNG. - .rotate
boolean
= true
- Enable image rotation.
- .imageDim
Array.<number>
- Specify image dimensions. e.g. [800, 600]
. Only for JPEG, PNG, and BMP files.
Local and cropped images will be resized (upscaled or downscaled) to the specified dimensions before uploading.
The original height to width ratio is maintained. To resize all images based on the width, set [width, null], e.g. [800, null].
For the height set [null, height], e.g. [null, 600]. - .imageMax
Array.<number>
- Specify maximum image dimensions. e.g. [800, 600]
. 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.
The output will not be exactly 800x600 unless the imageMax matches the aspect ratio of the original image. - .imageMin
Array.<number>
- Specify minimum image dimensions. e.g. [800, 600]
. Only for JPEG, PNG, and BMP files.
Images smaller than the specified dimensions will be upscaled to the minimum size while maintaining the original aspect ratio.
The output will not be exactly 800x600 unless the imageMin matches the aspect ratio of the original image. - .uploadConfig
object
- Options for local file uploads.
- .partSize
number
= 6 * 1024 * 1024
- Size of each uploaded part. This is overridden when intelligent ingestion is enabled. - .concurrency
number
= 3
- Max number of concurrent parts uploading (chunks of files, not whole files). - .intelligent
boolean
| string
- Enable/disable intelligent ingestion. If truthy then intelligent ingestion must be enabled in your Filestack application. Passing true/false toggles the global intelligent flow (all parts are chunked and committed). Passing 'fallback'
will only use FII when network conditions may require it (only failing parts will be chunked). - .intelligentChunkSize
number
- Set the default chunk size for intelligent part uploads. Defaults to 8MB on desktop, 1MB on mobile. - .retry
number
= 10
- Number of times to retry a failed part of the flow. - .retryFactor
number
= 2
- Base factor for exponential backoff. - .timeout
number
= 120000
- Time in milliseconds to wait before cancelling requests. - .onRetry
retryCallback
- Called when a retry is initiated.
- .storeTo
object
- Options for file storage.
- .location
string
- 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. - .onUploadStarted
onUploadStarted
- Called when uploading starts (user initiates uploading). - .onClose
function
- Called when the UI is exited. - .onOpen
function
- Called when the UI is mounted. - .rejectOnCancel
boolean
- Reject the returned Promise when a user cancels the pick. The Promise will reject with a list of all files currently selected. - .allowManualRetry
boolean
= false
- Prevent modal close on upload failure and allow users to retry. - .rootId
string
= "__filestack-picker"
- Id for the root DOM node of the mounted app. - .globalDropZone
boolean
- Toggle the drop zone to be active on all views. Default is active only on local file source. - .exposeOriginalFile
boolean
- When true the originalFile metadata will be the actual File object instead of a POJO. - .modalSize
Array.<number>
- Specify [width, height] in pixels of the desktop modal.
Example
client.pick({
maxFiles: 20,
uploadInBackground: false,
onOpen: () => console.log('opened!'),
})
.then((res) => {
console.log(res.filesUploaded)
console.log(res.filesFailed)
});
File metadata : object
The metadata available on uploaded files returned from pick.
Name | Type | Description |
---|
filename | string | Name of the file. |
handle | string | Filestack handle for the uploaded file. |
mimetype | string | The MIME type of the file. |
originalPath | string | The origin of the file, e.g. /Folder/file.jpg. |
size | number | Size in bytes of the uploaded file. |
source | string | The source from where the file was picked. |
url | string | The Filestack CDN URL for the uploaded file. |
originalFile | object | undefined | Properties of the local binary file. |
status | string | undefined | Indicates Filestack transit status. |
key | string | undefined | The hash-prefixed cloud storage path. |
container | string | undefined | The cloud container for the uploaded file. |
uploadId | string | A uuid for tracking this file in callbacks. |
onFileSelected : function
Params
- file
object
- File metadata.
Example
onFileSelected(file) {
if (file.size > 1000 * 1000) {
throw new Error('File too big, select something smaller than 1MB');
}
}
onFileSelected(file) {
file.name = 'foo';
return file;
}
onUploadStarted : function
Params
- files
array
- All currently selected files.
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.makeDropPane(paneOptions, [pickOptions])
Appends a drop zone into the DOM node specified by paneOptions.id
. This feature is powered by the picker and supports the validation and callback options through pickOptions
.
Params
- paneOptions
object
- .id
string
- Required: Id for the DOM node that will mount the drop pane. - .overlay
boolean
= true
- Toggle the full-page drop zone overlay. - .onDragEnter
function
- Callback for dragenter events. - .onDragLeave
function
- Callback for dragleave events. - .onDragOver
function
- Callback for dragover events. - .onDrop
function
- Callback for drop events. - .onSuccess
function
- Callback that is passed a list of uploaded file metadata. - .onError
function
- Callback that is passed a list of failed file metadata. - .onProgress
function
- Callback that is passed a number representing total progress percent for all dropped files. - .onClick
function
- Callback for drop pane click event. - .disableClick
boolean
- Disable file input on click. - .showIcon
boolean
= true
- Toggle icon element in drop pane. - .showProgress
boolean
= true
- Toggle upload progress display. - .customText
string
- Customize the text content in the drop pane. - .cropFiles
boolean
- Toggle the crop UI for dropped files.
- [pickOptions] - See the options for
client.pick
. fromSources
is ignored.
Example
<div id="dropzone" style="width:500px;height:300px;"></div>
client.makeDropPane({
id: 'dropzone',
onSuccess: res => console.log(res),
}, {
maxFiles: 2,
});
client.cropFiles(filesOrUrls, [pickOptions]) ⇒ Promise
⏏
Opens the crop UI for the specified list of files or URLs.
Resolve: object
- Object contains keys filesUploaded
and filesFailed
which are both arrays of file metadata.
Params
- filesOrUrls
array
- An array of URL or File/Blob values to transform. - [pickOptions] - See the options for
client.pick
. fromSources
is ignored.
Example
<input id="fileSelect" type="file">
const inputEl = document.getElementById('fileSelect');
const pickOptions = { transformations: { crop: true, circle: false } };
inputEl.addEventListener('change', (e) => {
client.cropFiles(e.target.files, pickOptions)
.then(res => console.log(res));
});
const urls = [
'https://d1wtqaffaaj63z.cloudfront.net/images/fox_in_forest1.jpg',
'https://d1wtqaffaaj63z.cloudfront.net/images/sail.jpg',
];
client.cropFiles(urls).then(res => console.log(res));
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, 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) => {
const urlCreator = window.URL || window.webkitURL;
const 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.preview(handle, [options])
Used for viewing files via Filestack handles, requires Document Viewer addon to account.
Opens document viewer in new window if ID option is not provided.
Params
- handle
string
- Valid Filestack handle. - [options]
object
- [.id]
string
- Id for iframe container element. - [.policy]
string
- Filestack security policy (overrides client session). - [.signature]
string
- Filestack security signature (overrides client session). - [.css]
string
- URL to custom CSS.
Example
client.preview('KW9EJhYtS6y48Whm2S6D', { id: 'previewId', css: 'https://www.linktoyourcss.com'});
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,
};
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.
- border
object
- Border options.
- .width
number
- .color
number
- .background
number
- monochrome
boolean
- Monochrome. - sepia
object
- Sepia.
- output
object
- Output options.
- .format
string
- .background
string
- .page
Array.<number>
- Range format [1, 10000]
. - .density
Array.<number>
- Range format [1, 500]
. - .compress
boolean
- .quality
number
| string
- Can be number in range 1-100 or input
. - .input
boolean
- .strip
boolean
- .colorspace
string
- One of rgb
, cmyk
, or input
. - .secure
boolean
- .docinfo
boolean
- .pageformat
string
- One of a3
, a4
, a5
, b4
, b5
, letter
, legal
, or tabloid
. - .pageorientation
string
- One of landscape
or portrait
.
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
| string
- must be a valid File, Blob, or base64 encoded string. - [uploadOptions]
object
- [.partSize]
number
= 6 * 1024 * 1024
- Size of each uploaded part. This is hardcoded to 8MB when intelligent ingestion is enabled. To control chunk sizes please use intelligentChunkSize
. - [.concurrency]
number
= 3
- Max number of concurrent parts uploading. - [.intelligent]
boolean
| string
- Enable/disable intelligent ingestion. If truthy then intelligent ingestion must be enabled in your Filestack application. Passing true/false toggles the global intelligent flow (all parts are chunked and committed). Passing 'fallback'
will only use FII when network conditions may require it (only failing parts will be chunked). - [.intelligentChunkSize]
number
- Set the default chunk size for intelligent part uploads. Defaults to 8MB on desktop, 1MB on mobile. - [.retry]
number
= 10
- Number of times to retry a failed part of the flow. - [.retryFactor]
number
= 2
- Base factor for exponential backoff. - [.retryMaxTime]
number
= 10000
- Upper bound in milliseconds for retry wait time. - [.timeout]
number
= 120000
- Time in milliseconds to wait before cancelling requests. - [.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();
token.resume();
token.cancel();
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.