Package Exports
- filestack-js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (filestack-js) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
filestack-js
Official browser client to the Filestack API's. Available via NPM and Filestack CDN.
Filestack documentation can be found here: https://filestack.com/docs/
This library is shipped as both a UMD module and a ES2015 module for modern Javascript bundlers. There is also a separate minified UMD module available on the Filestack CDN.
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:
(Note http://static.filestackapi.com/v3/filestack.js will always point to the latest version. This is not recommended for production.)
<script src="http://static.filestackapi.com/v3/filestack-0.6.2.js"></script>
<script>
const apikey = 'abc';
const client = filestack.init(apikey);
</script>
API Reference
- filestack
- init(apikey, [security]) ⇒
object
- .getSecurity() ⇒
object
- .setSecurity(security) ⇒
object
- .metadata(handle, [options]) ⇒
Promise
- .pick([options]) ⇒
Promise
- .remove(handle) ⇒
Promise
- .retrieve(handle, [options]) ⇒
Promise
- .storeURL(url, [options]) ⇒
Promise
- .transform(url, options) ⇒
string
- .upload(file, [uploadOptions], [storeOptions]) ⇒
Promise
- .getSecurity() ⇒
- version ⇒
string
- init(apikey, [security]) ⇒
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.
- .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.
- .policy
Example
client.setSecurity({ policy: 'policy', signature: 'signature' });
client.pick([options]) ⇒ Promise
Opens the picker UI.
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
- Defaultimagesearch
- Defaultfacebook
- Defaultinstagram
- Defaultgoogledrive
- Defaultdropbox
- Defaultwebcam
- Desktop only. Please uselocal_file_system
for mobile. Not currently supported in Safari or IE.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 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
- .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. - .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 ifaspectRatio
is defined and not 1.
- .aspectRatio
- .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.
- .crop
- .storeTo
object
- Options for file storage.- .location
string
= "s3"
- One ofs3
,gcs
,rackspace
,azure
,dropbox
. - .region
string
- Valid S3 region for the selected S3 bucket. S3 only. - .container
string
- .path
string
- .access
string
- One ofpublic
orprivate
.
- .location
- .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.
- .fromSources
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.
- .totalPercent
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 ofs3
,gcs
,rackspace
,azure
,dropbox
. - .mimetype
string
- .path
string
- .container
string
- .region
string
- Valid S3 region for the selected container (S3 only). - .access
string
- One ofpublic
orprivate
.
- .filename
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
- .metadata
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
- .size
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
- .x
- .dim
- resize
object
- Resize options. At least one option is required.- .width
number
- .height
number
- .fit
string
- One ofclip
,crop
,scale
,max
. - .align
string
- One ofcenter
,top
,bottom
,left
,right
,faces
, or align pair like['top', 'left']
.
- .width
- rotate
object
- Rotate options. At least one option is required.- .deg
number
|string
- Can be number in range 0-359 orexif
. - .exif
boolean
- .background
string
- .deg
- flip
boolean
- Flip image - flop
boolean
- Flop image - roundedCorners
object
- Rounded corners options.- .radius
number
|string
- Can be number in range 1-10000 ormax
. - .blur
number
- .background
string
- .radius
- vignette
object
- Vignette options.- .amount
number
- .blurmode
string
- One oflinear
orgaussian
. - .background
string
- .amount
- polaroid
object
- Polaroid options.- .color
string
- .rotate
number
- .background
string
- .color
- tornEdges
object
- Torn edges options.- .spread
Array.<number>
- Range format[10, 50]
. - .background
string
- .spread
- shadow
object
- Shadow options.- .blur
number
- .opacity
number
- .vector
Array.<number>
- Range format[25, 25]
. - .color
string
- .background
string
- .blur
- circle
object
- Circle options.- .background
string
- .background
- border
object
- Border options.- .width
number
- .color
number
- .background
number
- .width
- monochrome
boolean
- Monochrome. - sepia
object
- Sepia.- .tone
number
- .tone
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.
- [.partSize]
- [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 areprivate
orpublic
.
- [.filename]
- [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.
- .totalPercent
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.
- .location
© 2017 Filestack.