10K Views

OneDrive Filepicker

OneDrive Filepicker SDK can be used to get Files from OneDrive which you could use to show as shareable link or download as file.

Here are steps to Setup OneDrive FilePicker

Step 1:

Register application at https://apps.dev.microsoft.com/, Use a redirect URL of a page on your website (you will need to add OneDrive.js on that page). After registering App you will get an application id.

Step 2:

Use OneDrive picker as follow:

    <script type="text/javascript" src="https://js.live.net/v7.2/OneDrive.js" async="async"></script>
    <script type="text/javascript">
        launchOneDrivePicker = function(that) {
            var odOptions = {
                clientId: "YOUR_APPLICATION_ID",
                action: "query",
                multiSelect: false,
                advanced: {
                    redirectUri: "https://yourCommonRedirectUri.com",
                },
                openInNewWindow: true,
                success: function(response) {
                    $.each(response.value, function(index, value) {
                        var url = response.apiEndpoint + 'drives/' + value.parentReference.driveId + '/items/' + value.id;
                        $.ajax({
                            'url': url,
                            beforeSend: function(request) {
                                request.setRequestHeader("Authorization", 'Bearer ' + response.accessToken);
                            },                            
                            success: function(result) {
                                // console.log(result);
                                var resultData = {
                                    'url': result['@microsoft.graph.downloadUrl'], // this returns shareable url of file
                                    'name': result['name'], // this returns file name
                                };

                            },
                            error: function(xhr) {
                            },
                        });
                        
                    });
                },
                cancel: function() {
                  // called when user cancels popup action
                },
                error: function(e) {
                  // called when error in connecting to OneDrive api
                }
            };
            OneDrive.open(odOptions); //launches file picker
        };
    </script>

Note:

You can use single redirect URL instead of multiple when using file picker on many web pages. Define advanced option like:

advanced: {
            redirectUri: "https://yourCommonRedirectUri.com",
          },

 

Here is Official documentation and useful links for OneDrive File Picker:

https://dev.onedrive.com/sdk/js-v72/js-picker-open.htm

https://github.com/OneDrive/onedrive-api-docs

. . .