Opening Files with the OneDrive File Picker JavaScript SDK v7.2

The following walk through shows how to integrate the file picker SDK into your client-side JavaScript application.

1. Register your application

To use the OneDrive picker, you need to register your application through the Microsoft Application Registration Portal and receive an Application Id. You also need to add a valid redirect URI for your web application using the picker. This can either be the page hosting the picker SDK or a custom URL you define. For more information see Setting up.

2. Add a reference to the SDK

Embed the OneDrive JavaScript SDK into your page.

<script type="text/javascript" src="https://js.live.net/v7.2/OneDrive.js"></script>

3. Launch the file picker

To open files from OneDrive, your app should provide a button to programmatically open the OneDrive file picker. Because this code will launch a pop-up window in the browser, it needs to be called as part of an explicit user action to avoid being blocked by a pop-up blocker.

As part of the OneDrive.open(...) method, you specify the options for how the picker should behave and how the picker will call back to your code through and options object.

<script type="text/javascript">
  function launchOneDrivePicker(){
    var odOptions = { /* ... specify the desired options ... */ };
    OneDrive.open(odOptions);
  }
</script>
<button onClick="launchOneDrivePicker()">Open from OneDrive</button>

Note: When the OneDrive picker is opened, a new window with your page will open, and the SDK will use a query string to redirect the window to the picker. If the SDK is not present on your page on load (if it is lazy loaded in response to a user interaction, for example), the picker may not properly open. You may wish to use the redirectUri advanced option to redirect the popup to a page that loads the SDK without any user interaction.

Picker options

You can specify how the file picker behaves by providing an object with parameters that control the picker's behavior. This object also includes the callback functions for when the file picker is finished or encounters an error.

Example file picker options

var odOptions = {
  clientId: "INSERT-APP-ID-HERE",
  action: "query",
  multiSelect: true,
  advanced: {},
  success: function(files) { /* success handler */ },
  cancel: function() { /* cancel handler */ },
  error: function(error) { /* error handler */ }
}

Parameters

Parameter name Description
clientId The application ID generated by the app registration console for your integration.
action The action type being performed with the files selected. You can specify share to generate a sharable URL, download to receive a short-lived URL that downloads the content of the files, or query to return identifiers that can be used with the Microsoft Graph API or OneDrive API.
multiSelect The default value is false, which requires the user to select a single file only, or true to enable the user to select multiple files.
viewType The type of item that can be selected. The default value is files. You can specify folders to limit selection to only folders or specify all which enables the selection of both files and folders.
accountSwitchEnabled The default value is true, which renders the "Switch account" UI on the hosted File Picker page.
advanced A collection of additional properties which can further customize the behavior of the picker, but are not necessary for most scenarios. See Advanced options for more details.
success Called when the user finishes picking files and takes a response object that includes the collection of selected files. This is required if openInNewWindow is true.
cancel Called if the user cancels the picker. This function takes no parameters.
error Called when an error occurred on the server or the user doesn't have permission to get a link to the chosen file. This function takes one parameter, an error object.

Types of actions

Using the picker's action parameter you can specify which type of URL should be returned after the user selects a file or folder. The following values are allowed:

Value Description
download Returns the file's id, name and a short-lived download URL for the selected files.
share Returns a read-only sharing URL for the selected files that can be shared with other users.
query Returns metadata only for the selected files. Use the API to perform additional actions on the files accordingly.

4. Handling the picker response object

When the user is done picking file(s), the success callback receives response object. This object contains properties, include value property which is a collection of Item resource with a subset of the item's properties.

{
  "value": [
    {
      "id": "123456",
      "name": "document1.docx",
      "size": 12340,
      "@microsoft.graph.downloadUrl": "https://contoso-my.sharepoint.com/download.aspx?guid=1231231231a",
      "webUrl": "https://cotoso-my.sharepoint.com/personal/user_contoso_com/documents/document1.docx",
      "thumbnails": [
        {
          "id": "0",
          "small": { "url": "https://sn3302files.onedrive.live.com/..." },
          "medium": { "url": "https://sn3302files.onedrive.live.com/..." },
          "large": { "url": "https://sn3302files.onedrive.live.com/..." }
        }
      ]
    }
  ],
  "accessToken": "ey...",
  "apiEndpoint": "https://graph.microsoft.com"
}

Response properties

Property name Type Description
value Array of driveItems Metadata about the files that were selected.
webUrl Url Returned for multiple selection scenarios from OneDrive Personal accounts.
accessToken string The access token received by the file picker for your application. This can be used to make additional requests to Microsoft Graph without requiring another authentication flow.
apiEndpoint Url The API end point that the accessToken can be used with.

Advanced options

The picker also supports additional advanced scenarios. This allows the picker to be used alongside the OneDrive API to accomplish advanced scenarios.

The advanced parameter on the options object has the following defined properties:

Parameter name Description Scenarios
queryParameters A set of additional query parameters as specified by the OneDrive API that define how an item is returned. This typically includes a select and/or expand value. Query a file or folder
createLinkParameters Change the parameters used to generate a link for the share action. Share a file
filter A set of file types could be applied to display the specific types only. We support system type 'photo' and 'folder', and custom types of any extension like '.docx'. One applicable filter setting is "folder,.png" which each filter is separated by a ,. Display files
redirectUri By default the picker uses the page it was launched from as the redirect uri for authentication. This may not be desirable in all scenarios, so you can set a custom URL to use instead. This URL must be registered on your app's registration portal as a redirect URL. The target page must reference the OneDrive Picker SDK in the same fashion as the calling page. OAuth
endpointHint Endpoint hint is used for SDK redirects the app to the right OAuth endpoint based on which OneDrive API endpoints the app wants talk to. OneDrive API endpoints includes OneDrive personal, OneDrive for Business or SharePoint Online. The value of endpointHint could be api.onedrive.com for OneDrive personal, the OneDrive for Business URL or a SharePoint document library URL, ex. https://contoso-my.sharepoint.com/personal/foo_contoso_onmicrosoft_com/ or https://contoso.sharepoint.com/shared%20documents/. It is not required if the app talks to Microsoft Graph API. OAuth
accessToken An accessToken granted access to OneDrive API endpoints for OneDrive personal, OneDrive for Business, or SharePoint Online could be passed in skip the OAuth flow which gives you a faster experience. endpointHint is required if an accessToken is presented. OAuth
loginHint If a user has previously logged into your application, you can provide a loginHint value which will enable single sign-on. OAuth
isConsumerAccount When talks to Microsoft Graph API and the loginHint specified, SDK also requires the app to tell the logged in user is a consumer account (aka, Microsoft Account) or a business account. OAuth
scopes The SDK will automatically request the Files.Read.All scope for open flows, and Files.ReadWrite.All scope for save flows. However, if you wish to request additional permissions, you can add additional scopes here. OAuth
navigation In Picker SDK 7.2 we introduced new Picker UI which multiple configurations could be set. All configurations is under the navigation object. Picker UI

Note: Currently filter type 'photo' is only supported for OneDrive personal accounts.

Using the Picker and API together

You can use the action value query along with setting the queryParameters of the advanced object to return a custom set of properties from the API about the selected object. For example, when a file is picked, to include photo details (if available):

var odOptions = {
  clientId: "INSERT-APP-ID-HERE",
  action: "query",
  multiSelect: false,
  advanced: {
    queryParameters: "select=id,name,size,file,folder,photo,@microsoft.graph.downloadUrl",
    filter: "folder,.png" /* display folder and files with extension '.png' only */
  },
  success: function(files) { /* success handler */ },
  cancel: function() { /* cancel handler */ },
  error: function(error) { /* error handler */ }
}

This tells the picker SDK to select the id, name, size, file, folder, and photo properties in the response.

By default the OneDrive file picker returns a view-only sharing URL when action is set to share. However you can use the createLinkParameters property to change the parameters passed to the createLink action.

var odOptions = {
  clientId: "INSERT-APP-ID-HERE",
  action: "share",
  multiSelect: false,
  advanced: {
    createLinkParameters: { type: "edit", scope: "organization" }
  },
  success: function(files) { /* success handler */ },
  cancel: function() { /* cancel handler */ },
  error: function(error) { /* error handler */ }
}

Using a custom redirect URI

If your app is a large client-side JavaScript app or uses query string parameters to maintain state, it may not be desirable to use the page launching the file picker as the redirect URI. This requires that your whole app is reloaded inside the popup window, which may cause performance issues. You can specify an alternative redirect URI through the advanced object which is used instead.

var odOptions = {
  clientId: "INSERT-APP-ID-HERE",
  action: "download",
  advanced: {
    redirectUri: "https://contoso.com/filePickerRedirect.htm"
  },
  success: function(files) { /* success handler */ },
  cancel: function() { /* cancel handler */ },
  error: function(error) { /* error handler */ }
}

Using alternative API endpoints

Microsoft Graph API provides unified access to files stored on OneDrive personal, OneDrive for Business, and SharePoint Online. However, in some limited scenarios it may be required to use a specific SharePoint site URL instead of Microsoft Graph.

In this case, the app can specify the OneDrive API endpoint for the SharePoint site instead of the Microsoft Graph API endpoint. OneDrive Picker SDK will redirect to the right OAuth endpoint to get an access token. The mapping between the OneDrive API endpoints and the OAuth authority is:

API endpoint OAuth endpoint endpointHint
https://graph.microsoft.com/v1.0/ https://login.microsoftonline.com/common/oauth2/v2.0/authorize N/A
https://api.onedrive.com/v1.0/ https://login.live.com/oauth20_authorize.srf https://api.onedrive.com
https://contoso-my.sharepoint.com/personal/ryan_contoso_com/ https://login.microsoftonline.com/common/oauth2/authorize https://contoso-my.sharepoint.com/personal/ryan_contoso_com/

Redirects to MSA OAuth endpoint

var odOptions = {
  clientId: "INSERT-APP-ID-HERE",
  action: "query",
  advanced: {
    endpointHint: "api.onedrive.com",
  },
  success: function(files) { /* success handler */ },
  cancel: function() { /* cancel handler */ },
  error: function(error) { /* error handler */ }
}

Redirect to the document library directly, and the app controls the OAuth flow somewhere else.

var odOptions = {
  clientId: "INSERT-APP-ID-HERE",
  action: "download",
  advanced: {
    endpointHint: "https://contoso.sharepoint.com/shared%20documents/",
    accessToken "INSERT-ACCESS-TOKEN-HERE"
  },
  success: function(files) { /* success handler */ },
  cancel: function() { /* cancel handler */ },
  error: function(error) { /* error handler */ }

The page you redirect to needs only to load the OneDrive SDK script:

<html>
<script type="text/javascript" src="https://js.live.net/v7.2/OneDrive.js"></script>
</html>

Customize capabilities

While the file picker allows users to select files from across Office 365, including OneDrive and SharePoint document libraries, you may wish to restrict the source for where a file can be opened from. You can use these properties to restrict the capabilities to only those that you wish to enable:

Parameter name Description
disable If value set, navigation panel will not show up.
entryLocation Set the document library rendered in OneDrive picker UI.
sourceTypes Sources of files user can select on the navigation panel.

The app could specify sourceTypes like OneDrive, Recent, Sites or several sources in an array [`OneDrive`, `Recent`]. The app also could specify a customized entry location in stead of the default one by specify the entryLocation object. The customized entry location is limited to a SharePoint document library. Default entry location is the user's OneDrive for Business.

var odOptions = {
  clientId: "INSERT-APP-ID-HERE",
  action: "download",
  advanced: {
    navigation: {
      entryLocation: {
        sharePoint: {
          sitePath: "THE-SITE-PATH",
          listPath: "THE-LIST-PATH",
          itemPath: "THE-ITEM-PATH"
        }
      },
      sourceTypes: "Sites" /* or an array like ["OneDrive", "Sites"] */
    }
  },
  success: function(files) { /* success handler */ },
  cancel: function() { /* cancel handler */ },
  error: function(error) { /* error handler */ }