Build a Microsoft OneDrive API File Picker to Upload & Download Files to Storage in Browser Using Javascript Full Project For Beginners

 

 

Adding File Picker Library

 

 

<script type="text/javascript" src="https://js.live.net/v7.0/OneDrive.js"></script>
<button id="OpenOneDrive" type="button">Open from OneDrive</button>

 

 

const oneDriveApplicationId = "INSERT YOUR APPLICATION ID";

function launchOneDrivePicker() {
    return new Promise<OneDriveResult | null>((resolve, reject) => {
        var odOptions: OneDriveOpenOptions = {
            clientId: oneDriveApplicationId,
            action: "download",
            multiSelect: true,
            openInNewWindow: true,
            advanced: {
                //filter: "folder,.png" // Show only folders and png files
                //filter: "folder,photo" // Show only folders and photos
            },
            success: function (files) { resolve(files); },
            cancel: function () { resolve(null); },
            error: function (e) { reject(e); }
        };

        OneDrive.open(odOptions);
    });
}

Then, you can bind the click event of the button:

document.getElementById("OpenOneDrive").addEventListener("click", e => {
    e.preventDefault();
    launchOneDrivePicker()
        .then(result => {
            if (result) {
                for (const file of result.value) {
                    const name = file.name;
                    const url = file["@microsoft.graph.downloadUrl"];
                    console.log({ name: name, url: url });
                }
            }
        }).catch(reason => {
            console.error(reason);
        });
});

 

See also  Node.js Express Compress Files and Images to ZIP Files Using adm-zip Library Full Tutorial For Beginners 2020

#Downloading the file

Once you get the file URL, you can easily download the file in JavaScript:

fetch(url)
    .then(response => response.blob())
    .then(blob => {
        // TODO do something useful with the blob

        // For instance, display the image
        const url = URL.createObjectURL(blob);
        (<HTMLImageElement>document.getElementById("preview")).src = url;
    });

Leave a Reply