如何通过单个API调用下载指定OneDrive附件链接的文件?
Absolutely! You don’t need to slog through those multi-step folder-traversal API calls anymore. Microsoft Graph supports direct path-based addressing for OneDrive items, which lets you download your target file in a single request.
Here’s how to build the call:
First, break down your original OneDrive link:
https://company-my.sharepoint.com/personal/drive_name/Documents/Microsoft Teams Chat Files/hr.pak
Extract two key details:
- User Principal Name (UPN): The
drive_namein the URL is a URL-encoded version of the user’s UPN (for example, if the actual UPN isjane.smith@company.com, SharePoint might encode it asjane_smith_company_com). Convert this back to the user’s real UPN (you can confirm this via the Microsoft 365 admin center or a quickGET https://graph.microsoft.com/v1.0/userscall to list organization users). - Relative File Path: The path to the file from the OneDrive root:
/Documents/Microsoft Teams Chat Files/hr.pak
Plug these into this single Graph API request:
GET https://graph.microsoft.com/v1.0/users/{userPrincipalName}/drive/root:/Documents/Microsoft Teams Chat Files/hr.pak:/content
How this works:
- The
:/{path}:/contentsyntax tells Graph to directly locate the item at the specified path under the user’s OneDrive root, then return its raw binary content immediately. - This call will send back the file’s binary data, which you can save directly as
hr.pakusing your HTTP client or browser.
Alternative (if you have the Drive Item ID):
If you already have the unique driveItemId of the file (you can grab this once via a quick path lookup), you can use this even shorter call:
GET https://graph.microsoft.com/v1.0/drives/{driveId}/items/{driveItemId}/content
But for your scenario, the path-based approach is more straightforward since you already have the file’s location from the SharePoint link.
内容的提问来源于stack exchange,提问作者Sameer

