Chooser

Using the Chooser

The Chooser is the fastest way to get files from Dropbox into your web app. It's a small JavaScript component that enables your app to get files from Dropbox without having to worry about the complexities of implementing a file browser, authentication, or managing uploads and storage.

This tutorial will guide you through everything you need to do to add the Chooser to your app and customize it to suit your use cases.

Demo

Click the button below to see the Chooser in action. This demo triggers a Chooser, which lets you choose a file from your Dropbox. Once a file is selected, the link is returned to the host website.

Options:
Link type:
Chooser button:
Returns:
Choose something from Dropbox to see the return value

Setup

The first step in adding the Chooser to your app is to create an app. Using the Chooser doesn't require production approval, so you can publish your integration to your users as soon as you're ready.

When you create a Chooser app for the web, you'll need to provide the domain names where your app is hosted. This lets us stop other websites from trying to impersonate your app. If you're developing locally, you can use localhost as the domain name as well.

Once you've created a new app, add the following JavaScript snippet to your HTML. Use the pull-down menu below to select your Dropbox app and the app key will be pre-filled for you.

Sign in to see your apps or create a new app.
Generic embed code (insert your app key)
<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="YOUR_APP_KEY"></script>

Triggering the Chooser from JavaScript

There are two ways to trigger the Chooser on your website. To create the nice styled button you see in the demo above, you can use the following JavaScript:

var button = Dropbox.createChooseButton(options);
document.getElementById("container").appendChild(button);

If you prefer to design a custom button instead, you can trigger the Chooser directly from JavaScript using the following method:

Dropbox.choose(options);

Note that the Chooser opens in a pop-up window, so you should only call this function from within a user-triggered event handler such as a tap or click event. Otherwise, the pop-up will likely be blocked by the browser.

Both methods take a single options parameter with the following fields:

options = {

    // Required. Called when a user selects an item in the Chooser.
    success: function(files) {
        alert("Here's the file link: " + files[0].link)
    },

    // Optional. Called when the user closes the dialog without selecting a file
    // and does not include any parameters.
    cancel: function() {

    },

    // Optional. "preview" (default) is a preview link to the document for sharing,
    // "direct" is an expiring link to download the contents of the file. For more
    // information about link types, see Link types below.
    linkType: "preview", // or "direct"

    // Optional. A value of false (default) limits selection to a single file, while
    // true enables multiple file selection.
    multiselect: false, // or true

    // Optional. This is a list of file extensions. If specified, the user will
    // only be able to select files with these extensions. You may also specify
    // file types, such as "video" or "images" in the list. For more information,
    // see File types below. By default, all extensions are allowed.
    extensions: ['.pdf', '.doc', '.docx'],
};

Handling the response

The files parameter in the above success callback function will be an array of file objects, each containing info about the selected file. If multiselect is false, the array will contain a single item. Each file object includes the following fields:

file = {

    // Name of the file.
    name: "filename.txt",

    // URL to access the file, which varies depending on the linkType specified when the
    // Chooser was triggered.
    link: "https://...",

    // Size of the file in bytes.
    bytes: 464,

    // URL to a 64x64px icon for the file based on the file's extension.
    icon: "https://...",

    // A thumbnail URL generated when the user selects images and videos.
    // If the user didn't select an image or video, no thumbnail will be included.
    thumbnailLink: "https://...?bounding_box=75&mode=fit",

    // Boolean, whether or not the file is actually a directory
    isDir: false,
};

The thumbnail link contains query string parameters that specify how the thumbnail is generated. By modifying these parameters, you can construct URLs for other sizes and modes of thumbnails:

  • bounding_box Bounding box size for the thumbnail which must be one of the following values: 75 (default), 256, 800, 1280, 2048.
  • mode One of the following resize modes:
    • fit default Shrink the original image maintaining the original aspect ratio until the entire image fits inside the bounding box.
    • crop Shrink the original image until its width or height fits in bounding box, then crop anything outside the bounding box.
    • fit_one_and_overflow Shrink the original image until its width or height fits into the bounding box but do not crop the left overs. The returned image will be larger than the bounding box. This is useful for situations where you need to use a square thumbnail but also want to use that image as a placeholder while you load a higher resolution version in the background.

The Chooser can be configured to return one of two link types.

  • preview links are the default type of link returned by the Chooser. Preview links point to a human-friendly preview page of a file and are great for sharing. You can read more about links to Dropbox files in our Help Center. Note that users may disable this link at a later point if they choose.
  • direct links point directly to the contents of the file and are useful for downloading the file itself. Unlike preview links, however, they will expire after four hours, so make sure to download the contents of the file immediately after the file is chosen. Direct links also support CORS, which allows you to read the file information directly in the browser using client-side JavaScript. These URLs should not be used to display content directly in the browser.

File types

In addition to individual file extensions, the extensions parameter in JavaScript allows the following file types: images, audio, video, documents, and text. Each file type corresponds to a list of individual file extensions, as defined in the developer guide.

Supported browsers

Not all browsers support the Chooser. If a user's browser doesn't support the Chooser, we'll gray out the button and show a warning message if you try to call Dropbox.choose(). You can check to see if the user's browser is supported by calling Dropbox.isBrowserSupported().

The Chooser supports the following browsers:

Desktop

  • Internet Explorer, versions 9+
  • Chrome
  • Firefox
  • Safari

Mobile

  • Safari
  • Android browser
  • Chrome on Android

Using the Chooser

The Chooser is the fastest way to get files from Dropbox into your Android app. It's a small library that enables your app to access files from Dropbox without having to worry about the complexities of implementing a file browser, OAuth, or managing uploads and storage. Take a look at a screenshot of what the Chooser looks like inside an Android app.

This tutorial will guide you through everything you need to do to add the Chooser to your app and customize it to suit your use cases.

Setup

The Android Chooser SDK zip contains a DropboxChooserSDK Android library project.

You'll also need to create a new app here if you haven't already as you'll need the App key below.

Adding the Chooser to an Android Studio project

You'll need to add the DropboxChooserSDK to Android Studio and then add it as a dependency in your project.

Creating the new module

  1. Open Android Studio, go to File → New Module → Import Existing Project (Eclipse ADT or Gradle Project) → and press Next
  2. Press the "..." button next to the Source Directory field and select the DropboxChooserSDK folder you just unzipped. Press Next.
  3. Go through the rest of the module creation flow. Click Next again, and then click Finish.
  4. You should now have a DropboxChooserSDK module in your project.

Adding the dependency

  1. Within Android Studio, switch to the "project view".
  2. Right click on the app module and click Open Module Settings.
  3. Select the Dependencies tab.
  4. In the lower left corner, click the "+" (Add) button, select Module dependency and select the dropboxChooserSDK module.
  5. Click OK, and then click OK again. You may have to wait for Gradle to sync.

Adding the Chooser to an Eclipse project

You'll need to add the DropboxChooserSDK to Eclipse and then reference it in your project.

Creating the new project

  1. Open Eclipse, go to File → New → Other → Android → Android Project from Existing Code and press Next
  2. Press Browse next to the Root Directory field and select the DropboxChooserSDK folder you just unzipped. Press Finish.
  3. You should now have a DropboxChooserSDK project.

Referencing the project

  1. In Eclipse, right click on your existing project and click Properties.
  2. In the menu on the left hand side, select Android.
  3. In the lower Library section, click Add and select the DropboxChooserSDK project.

Example app

The Android Chooser SDK zip also contains a ChooserExample Android app project that implements an expanded version of the code below. Open it and follow along with the rest of this guide.

Triggering the Chooser

Your app should give the user a button or action that asks them to select a file from Dropbox. This example sets up a click handler in onCreate() for a button called chooser_button that will trigger the Chooser. You'll need to add a button with the same name to your layout as well.

In this example, we'll request a preview link type using DbxChooser.ResultType.PREVIEW_LINK (read more about link types below). This example also uses an Activity but it works just as well with a Fragment.

Be sure to replace APP_KEY with the real value for your app.
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.dropbox.chooser.android.DbxChooser;

static final int DBX_CHOOSER_REQUEST = 0;  // You can change this if needed

private Button mChooserButton;
private DbxChooser mChooser;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mChooser = new DbxChooser(APP_KEY);

    mChooserButton = (Button) findViewById(R.id.chooser_button);
    mChooserButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mChooser.forResultType(DbxChooser.ResultType.PREVIEW_LINK)
                    .launch(MainActivity.this, DBX_CHOOSER_REQUEST);
        }
    });
}

The Chooser coordinates with the Dropbox app to allow the user to select files without having to worry about the usual authorization flow. In order to handle the response when the user returns to your app, you'll need to add a hook to onActivityResult():

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == DBX_CHOOSER_REQUEST) {
        if (resultCode == Activity.RESULT_OK) {
            DbxChooser.Result result = new DbxChooser.Result(data);
            Log.d("main", "Link to selected file: " + result.getLink());

            // Handle the result
        } else {
            // Failed or was cancelled by the user.
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

If the user cancels, resultCode will be Activity.RESULT_CANCELED. A successful choice will be Activity.RESULT_OK. In the case of a successful choice, you can create a new DbxChooser.Result to handle the response.

Handling the response

The DbxChooser.Result created in the onActivityResult() callback will contain the info about the selected file.

public static class Result {

    // URI to access the file, which varies depending on the link type specified when
    // the Chooser was triggered
    public Uri getLink() { ... }

    // Name of the file
    public String getName() { ... }

    // URI to a 64px x 64px icon for the file based on the file's extension
    public Uri getIcon() { ... }

    // Size of the file in bytes
    public long getSize() { ... }

    // Set of thumbnail URIs generated when the user selects images and videos. It
    // returns three sizes with the keys: 64x64px, 200x200px, and 640x480px.
    // If the user didn't select an image or video, no thumbnails will be included.
    public Map<String, Uri> getThumbnails() { ... }

}

The Chooser can be configured to return one of three link types.

  • ResultType.PREVIEW_LINKlinks are the default type of link returned by the Chooser. Preview links point to a human-friendly preview page of a file and are great for sharing. You can read more about links to Dropbox files in our Help Center. Note that users may disable this link at a later point if they choose.

  • ResultType.DIRECT_LINKlinks point directly to the contents of the file and are useful for downloading the file itself. Unlike preview links, however, they will expire after four hours, so make sure to download the contents of the file immediately after the file is chosen. These URLs should not be used to display content directly in the browser.

  • ResultType.FILE_CONTENTlinks (Android only) point to the actual file on the local device and let your app take advantage of files cached by the Dropbox app. However, these files are temporary and can be cleaned up by the operating system at any point, so you should copy it and manage it within your app if you need to keep the contents of a file.

Android API support

The Android Chooser SDK includes the Android Support Library and is written to support Android API version 8 and higher. To support Android API versions 8, 9, and 10, your app must extend Activity or android.support.v4.app.FragmentActivity instead of Fragment. If it doesn't, you'll see the following error in LogCat when using the Android Chooser on these older versions:

The Chooser requires Fragments. If below API level 11, pass in a FragmentActivity from the support library.

Also, the Android Support Library that is bundled with the Chooser may conflict with the support library in your project if your project has a different version. If you see a "Jar mismatch! Fix your dependencies" error in the Console, delete android-support-v4.jar in the libs directory of DropboxChooserSDK and copy the version of android-support-v4.jar from your project into that folder.

Using the Chooser

The Chooser is the fastest way to get files from Dropbox into your iOS app. It's a small framework that enables your app to access files from Dropbox without having to worry about the complexities of implementing a file browser, OAuth, or managing uploads and storage. Take a look at a screenshot of what the Chooser looks like on iOS.

This tutorial will guide you through everything you need to do to add the Chooser to your app and customize it to suit your use cases.

Setup

The iOS Chooser SDK zip contains DBChooser.framework and DBChooser.bundle.

You'll also need to create a new app here if you haven't already, as you'll need the App key below.

Adding the Chooser SDK to your project

  1. Open your project in Xcode.
  2. Navigate to where you downloaded the SDK and drag the DBChooser.framework and DBChooser.bundle folders into your project in Xcode.
  3. A confirmation dialog will pop up. Make sure Copy items ... is selected, then press Finish.

Creating a URL scheme

The Chooser coordinates with the Dropbox app to allow the user to select files without having to worry about the usual authorization flow. But in order to smoothly hand the user back to your app, you need to add a unique URL scheme that Dropbox can call. You'll need to configure your project to add one:

  1. Click on your project in the Project Navigator, select the Target option on the left, choose the Info tab, expand the URL Types section at the bottom, and press the + button.
  2. In the URL Schemes enter db-APP_KEY (replacing APP_KEY with the key generated when you created your app).

For iOS 9+, you'll also need to add the Dropbox URL Scheme to your list of allowed schemes.

  1. Open your YourApp-Info.plist file and add the key LSApplicationQueriesSchemes.
  2. Under LSApplicationQueriesSchemes, add two new items with the values dbapi-1 and dbapi-3.

The source code for your Info.plist file should now have the following:

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>dbapi-1</string>
  <string>dbapi-3</string>
</array>

Example app

The iOS Chooser SDK zip also contains a ChooserExample Xcode project that implements an expanded version of the code below. Open it and follow along with the rest of this guide.

Triggering the Chooser

Your app should give the user a button or action that asks them to select a file from Dropbox. This example uses a didPressChooser IBAction to your view controller to trigger the Chooser. You'll need to connect it to a button in Interface Builder.

This example requests a preview link type using DBChooserLinkTypePreview which is explained more in the Link types section below.

Your top view controller
#import <DBChooser/DBChooser.h>

- (void)didPressChoose
{
    [[DBChooser defaultChooser] openChooserForLinkType:DBChooserLinkTypePreview
                                    fromViewController:self completion:^(NSArray *results)
    {
        if ([results count]) {
            // Process results from Chooser
        } else {
            // User canceled the action
        }
    }];
}

The Chooser coordinates with the Dropbox app to allow the user to select files without having to worry about the usual authorization flow. In order to handle the response when the user returns to your app, you'll need to add a hook to -application:openURL:sourceApplication:annotation: in your AppDelegate:

YourAppDelegate.m
#import <DBChooser/DBChooser.h>

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url
    sourceApplication:(NSString *)source annotation:(id)annotation
{

    if ([[DBChooser defaultChooser] handleOpenURL:url]) {
        // This was a Chooser response and handleOpenURL automatically ran the
        // completion block
        return YES;
    }

    return NO;
}

That's it! The handleOpenURL: hook will call the completion block when control returns to your app. Now you can handle the results parameter of the completion block.

Handling the response

The results parameter passed to the completion block will be an NSArray of DBChooserResult objects, each containing info about the selected file. Currently, the array will contain a single DBChooserResult object. If the user cancels the Chooser, the results parameter will be nil.

@interface DBChooserResult : NSObject

// URL to access the file, which varies depending on the link type specified when the
// Chooser was triggered
@property NSURL *link;

// Name of the file
@property NSString *name;

// Size of the file in bytes
@property long long size;

// URL to a 64x64px icon for the file based on the file's extension.
@property NSURL *iconURL;

// Set of thumbnail URLs generated when the user selects images and videos. It returns
// three sizes with the keys: 64x64px, 200x200px, and 640x480px. If the user didn't
// select an image or video, no thumbnails will be included.
@property NSDictionary *thumbnails;

@end

The Chooser can be configured to return one of two link types.

  • DBChooserLinkTypePreviewlinks are the default type of link returned by the Chooser. Preview links point to a human-friendly preview page of a file and are great for sharing. You can read more about links to Dropbox files in our Help Center. Note that users may disable this link at a later point if they choose.

  • DBChooserLinkTypeDirectlinks point directly to the contents of the file and are useful for downloading the file itself. Unlike preview links, however, they will expire after four hours, so make sure to download the contents of the file immediately after the file is chosen. These URLs should not be used to display content directly in the browser.

Handling multiple app keys

The example uses the defaultChooser, which is created and initialized with the URL Scheme you registered during setup. You may have a project that requires multiple app keys because it also uses another Dropbox API. In this case, you'll need to explicitly initialize your own instance of the Chooser with the right app key by using the -initWithAppKey: method.