bloodleh
bloodleh

Reputation: 555

Create a permanent public download link to OneDrive file using Microsoft Graph

I'm trying to get a permanent public download link to OneDrive file using Microsoft Graph API. The goal is to have <img src="DOWNLOAD_LINK"> on my website and the OneDrive image file works for any user who views the page.

Currently I have tried the following things:

  1. GET https://graph.microsoft.com/beta/me/drive/root:/PATH/TO/FILE.png (doc) which returns

    • @microsoft.graph.downloadUrl : Public download link but expires after 1 hour.
    • webUrl : Private download link, requires authentication.

.

  1. POST https://graph.microsoft.com/beta/me/drive/root:/PATH/TO/FILE.png:/createLink (doc) with JSON body
{
    "type": "view",
    "scope": "anonymous"
}

which returns

.

  1. https://stackoverflow.com/a/37951378/2219407

    Using previous link.webUrl to generate a download url (doc):

$linkWebUrl = "https://domain-my.sharepoint.com/:i:/g/personal/username_domain/RANDOMTOKEN";
$b64 = base64_encode($linkWebUrl);
$b64 = trim($b64, "=");
$b64 = str_replace("/", "_", $b64);
$b64 = str_replace("+", "-", $b64);

$url = "https://api.onedrive.com/v1.0/shares/u!" . $b64 . "/root/content";

but it returns

{"error":{"code":"invalidRequest","message":"Invalid shares key."}}

I think this is because I am mixing the Graph and OneDrive APIs so it doesn't recognize the key? Replacing api.onedrive.com with graph.microsoft.com doesn't work either as Graph requires the usual Authorization header.

Anyone know anything that works?

Upvotes: 5

Views: 6190

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59358

You was very close but instead of step 3, download=1 url query parameter needs to be appended to generated sharing link to create a download link, for example:

https://{tenant}-my.sharepoint.com/:i:/g/personal/{account-name}_onmicrosoft_com/{token}?download=1

That's it.

Just a side note regarding the the error which occurs in step 3.

A sharing link generated for OneDrive for Business or SharePoint (https://tenant-my.sharepoint.com) could not be utilized via OneDrive Personal (https://api.onedrive.com) shares endpoint

Upvotes: 6

Related Questions