Filestack JavaScript SDK

repository·master·Indexed 42 days ago

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

Official JavaScript library (v3.51.6) for interacting with the Filestack API and content management system. Provides tools for multi-part uploading, image, video, and audio transformations via URL, and the Filestack Picker widget for web-based file selection. Includes the CloudClient for managing assets in cloud services like Google Drive and Dropbox, and utilities for normalizing file inputs via getFile().

Tokens
12.4K
Snippets
48
Records
55
Agent score
52%

What's inside Filestack

  1. How the Filestack Picker works

    master

    The Filestack Picker is an upload widget that can be initialized from a Filestack client instance using client.picker(options).

    Once initialized, the returned picker instance provides the following control methods:

    • open(): Creates the application and mounts it into the DOM based on the displayMode provided in options.
    • close(): Closes the application and removes its resources from the DOM.
    • crop(files): Creates the application, mounts it, and pre-selects the specified files for cropping.
    • cancel(): Cancels all uploads currently controlled by this picker instance.
    // Example initialization
    const picker = client.picker({
      // options from https://filestack.github.io/filestack-js/interfaces/pickeroptions.html
    });
    
    // Controlling the picker
    picker.open();
  2. Generate transformation URLs with Filelink

    master

    The Filelink class is used to programmatically build Filestack transformation URLs. You initialize it with a file handle or an external URL and an API key, then chain transformation methods to define how the file should be processed. Finally, calling .toString() generates the complete URL.

    Key Workflow:

    1. Instantiate Filelink with a source and API key.
    2. Chain transformation methods (e.g., .resize(), .rotate(), .smartCrop()).
    3. Call .toString() to get the URL.

    Note: If using external sources, an apikey is required.

    import { Filelink } from 'filestack-js'; // Assuming standard export
    
    const link = new Filelink('https://example.com/image.jpg', 'YOUR_API_KEY');
    link.resize({ width: 500, height: 500 }).rotate({ deg: 90 });
    
    console.log(link.toString());
    // Output: https://cdn.filestackapi.com/YOUR_API_KEY/resize=width:500,height:500/rotate=deg:90/https://example.com/image.jpg
  3. Configure Filelink for Base64 support

    master

    By default, Filestack URLs use standard encoding. To avoid issues with special characters in complex transformation parameters or long source URLs, you can enable Base64 encoding using .setBase64(true). When enabled, both the transformation string and the source URL are Base64 encoded within the final URL.

    Usage: Call .setBase64(true) on your Filelink instance before calling .toString().

    const link = new Filelink('https://example.com/image.jpg', 'YOUR_API_KEY');
    link.setBase64(true).resize({ width: 500 });
    
    console.log(link.toString());
  4. Configure Client Security with Policy and Signature

    master

    To protect your Filestack account and limit client capabilities, you should use server-side generated security policies and signatures. You can set these during initialization via ClientOptions or dynamically using setSecurity().

    Using ClientOptions:

    const client = filestack.init('apikey', {
      security: {
        policy: 'YOUR_POLICY',
        signature: 'YOUR_SIGNATURE'
      }
    });

    Using setSecurity():

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

    Note: Both policy and signature are required when providing a security object.

    const client = filestack.init('apikey', {
      security: {
        policy: 'YOUR_POLICY',
        signature: 'YOUR_SIGNATURE'
      }
    });
  5. Initialize the Filestack Client

    master

    To use Filestack, you must initialize a Client instance with your API key. This instance serves as the entry point for all Filestack operations including uploading, transforming, and managing files.

    ES Module usage:

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

    UMD (Browser) usage:

    <script src="https://static.filestackapi.com/filestack-js/3.x.x/filestack.min.js"></script>
    <script>
      const client = filestack.init('apikey');
    </script>
    import * as filestack from 'filestack-js';
    const client = filestack.init('apikey');
  6. Debug Filestack-js

    master

    The SDK uses the debug library. You can enable debug logging by setting the DEBUG environment variable to fs.*.

    Node.js

    Set the environment variable before running your script:

    DEBUG=fs.* node example_upload.js

    Browser

    Enable debugging via localStorage and then refresh the page:

    localStorage.debug = 'fs:*';
    // Browser instruction
    localStorage.debug = 'fs:*';
  7. Initialize the Filestack client in a Browser (ES Module)

    master

    If you are using a modern bundler (like Webpack, Rollup, or Parcel) in a browser environment, import the library as an ES module and initialize the client with your API key.

    import * as filestack from 'filestack-js';
    const client = filestack.init('apikey');
  8. Initialize the Filestack client via UMD (Script Tag)

    master

    For non-module browser environments, include the Filestack library via a <script> tag from the Filestack CDN. The filestack object will be available globally.

    <script src="//static.filestackapi.com/filestack-js/3.x.x/filestack.min.js" crossorigin="anonymous"></script>
    <script>
      const client = filestack.init('apikey');
    </script>
  9. Handle upload errors with the upload.error event

    master

    To capture all upload request errors, listen for the upload.error event on the client instance. The error object contains a details field which includes the responseBody, responseHeaders, and a code (specifically when the error type is FilestackErrorType.REQUEST).

    Note: An upload abort will throw a FilestackError with the type FilestackErrorType.ABORTED.

    const client = filestack.init('apikey');
    client.on('upload.error', (filestackError) => {
      console.log(filestackError);
    });
  10. Configure PickerOptions for file selection and behavior

    master

    The PickerOptions object allows you to customize the file picker's behavior, sources, and UI. Key configuration areas include:

    File Restrictions

    • accept: Restrict file types (e.g., .pdf, image/*, video/*).
    • acceptFn: A custom async function for advanced validation. It receives PickerAcceptFnOptions which includes mimeFromMagicBytes for deep inspection.
    • maxFiles / minFiles: Set limits on the number of files.
    • maxSize: Restrict files by maximum bytes.

    Sources and Display

    • fromSources: Array of allowed sources (e.g., local_file_system, url, facebook, googledrive, webcam).
    • displayMode: Choose between 'inline', 'overlay' (default), or 'dropPane'.
    • container: The DOM element where the picker should be appended (relevant for inline and dropPane).

    Image Transformations

    • transformations: Configure crop, circle, and rotate options.
    • imageDim / imageMax / imageMin: Specify target dimensions for resizing images before upload.
    • cleanupImageExif: Boolean or object to control EXIF data cleaning.

    Callbacks

    • onFileSelected: Triggered when a user selects a file. Can be used to veto selection (by throwing an error) or rename local files (by returning a new file object).
    • onUploadDone: Triggered when all uploads are complete. Returns a PickerResponse containing filesUploaded and filesFailed arrays.
    • onFileUploadProgress: Provides progress events for local multi-part uploads.