You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Microsoft Graph API获取OneDrive最新照片缩略图的技术求助

Solution to Get Latest OneDrive Photos with Thumbnails

Let's tackle your two requirements step by step, and adjust the sample code to fit your needs:

1. Retrieve All Photos (Including Subfolders) with Thumbnails in One Request

Instead of fetching folders one by one, you can use Microsoft Graph's search functionality to recursively pull all image files under the Photos special folder. This returns all photos (from every subfolder) directly, along with their thumbnails—no need to iterate through each folder individually.

We'll use:

  • search(q='') to traverse all items under the Photos root (since the Photos folder only contains images, an empty search returns all items)
  • $expand=thumbnails to include thumbnail data in the response
  • $filter=Image ne null to ensure we only get valid image files (optional but adds safety)

2. Sort by Creation Date (Descending)

Add the $orderby=createdDateTime desc parameter to your request to sort photos from newest to oldest automatically.


Modified Code for ItemsController

I renamed the method for clarity, but you can adjust it to fit your existing code structure:

using Models;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Graph;

public class ItemsController
{
    private GraphServiceClient graphClient;

    public ItemsController(GraphServiceClient graphClient)
    {
        this.graphClient = graphClient;
    }

    /// <summary>
    /// Gets all photos (including subfolders) from OneDrive Photos, sorted newest to oldest, with thumbnails.
    /// </summary>
    /// <returns>Collection of latest photos with thumbnails.</returns>
    public async Task<ObservableCollection<ItemModel>> GetLatestPhotos()
    {
        ObservableCollection<ItemModel> results = new ObservableCollection<ItemModel>();

        // Request all photos under the Photos special folder, sorted by creation date descending
        var photoRequest = graphClient.Me.Drive.Special["photos"].Root
           .Search("") // Empty search returns all items in Photos and subfolders
           .Request()
           .Select("id,name,createdDateTime") // Select only necessary fields to reduce payload size
           .Expand("thumbnails") // Include thumbnail data directly in the response
           .Filter("Image ne null") // Ensure we only process image files
           .OrderBy("createdDateTime desc"); // Sort from newest to oldest

        var photoPage = await photoRequest.GetAsync();
        var allPhotos = new List<DriveItem>(photoPage.CurrentPage);

        // Handle pagination (Graph returns max 200 items per page by default)
        while (photoPage.NextPageRequest!= null)
        {
            photoPage = await photoPage.NextPageRequest.GetAsync();
            allPhotos.AddRange(photoPage.CurrentPage);
        }

        // Convert Graph DriveItems to your custom ItemModel
        foreach (var photo in allPhotos)
        {
            results.Add(new ItemModel(photo));
        }

        return results;
    }
}

Key Changes Explained:

  • Recursive Photo Fetch: Using Search("") on the Photos root ensures we capture images from every nested subfolder in one go, eliminating the need to loop through folders manually.
  • Built-in Sorting: The OrderBy("createdDateTime desc") parameter handles sorting directly in the API request, so you don't need to sort results client-side.
  • Thumbnail Expansion: Expand("thumbnails") pulls thumbnail data into the initial response, so you won't need extra requests for each photo's thumbnail.
  • Pagination Handling: Added code to handle cases where you have more than 200 photos (Graph's default page limit).

Alternative: Deep Expand (For Limited Subfolder Levels)

If you prefer not to use search (e.g., for very specific folder structures), you can use deep $expand—but note this only works for a fixed number of subfolder levels:

var itemRequest = graphClient.Me.Drive.Special["photos"].Root
   .Request()
   .Expand("children($expand=thumbnails,$filter=Image ne null), children/children($expand=thumbnails,$filter=Image ne null)")
   .OrderBy("createdDateTime desc");

This covers two levels of subfolders, but search is still the better choice for unlimited recursion.


内容的提问来源于stack exchange,提问作者Kevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:48:36