簡體   English   中英

如何使用 Microsoft Graph API rest 調用在 c# 中上傳超過 4MB

[英]How to upload more than 4MB in c# using Microsoft Graph API rest calls

我沒有將超過 4MB 的文件上傳到 OneDrive,我已經成功地創建了文件夾、重命名、刪除,甚至上傳了一個 4MB 或更少的文件,但是上傳超過 4MB 的文件似乎有點復雜。 我一直試圖通過查看此解決方案來了解如何使用 Microsoft Graph API rest 調用在 c# 中上傳大型文檔

有兩種解決方案。 票數較高的解決方案建議使用冗長的方法(但是不推薦使用 function“GetChunkRequestResponseAsync”,並且我無法找到合適的 function 來執行相同的操作),但是當我第二個解決方案使用“new LargeFileUpload”時把它放在我的代碼(Visual Studio)中,它告訴我只有“LargeFileUploadTask <? >”存在(外觀相同的function但是最后有一個“任務”。我不明白該放什么“任務<字符串> ???”。

無論如何,我絕對理解必須請求 uploadSession:

var uploadSession = await _client.Drive.Items[FolderID]
                    .ItemWithPath(Name)
                    .CreateUploadSession()
                    .Request()
                    .PostAsync();
var maxChunkSize = 320 * 1024; //320 KB chunk sizes 

它可能涉及將數據存儲到字節數組中,例如:

string FilePath = "D:\\MoreThan5MB.txt";
string path = FilePath;//Actual File Location in your hard drive       

byte[] data = System.IO.File.ReadAllBytes(path);  //Stores all data into byte array by name of "data" then "PUT to the root folder

Stream stream = new MemoryStream(data);

但任何幫助和建議將不勝感激。 如果這意味着什么,這里是一個幫助我上傳小於 4MB 的鏈接: How to upload to OneDrive using Microsoft Graph Api in c#謝謝

自從問題發布以來,微軟使大文件的上傳變得更加容易。 我目前正在使用 MS Graph 1.21.0。 此代碼應進行一些小的調整:

    public async Task<DriveItem> UploadToFolder(
        string driveId,
        string folderId,
        string fileLocation,
        string fileName)
    {
        DriveItem resultDriveItem = null;

        using (Stream fileStream = new FileStream(
                    fileLocation,
                    FileMode.Open,
                    FileAccess.Read))
        {
            var uploadSession = await _graphServiceClient.Drives[driveId].Items[folderId]
                                    .ItemWithPath(fileName).CreateUploadSession().Request().PostAsync();

            int maxSlice = 320 * 1024;

            var largeFileUpload = new LargeFileUploadTask<DriveItem>(uploadSession, fileStream, maxSlice);

            IProgress<long> progress = new Progress<long>(x =>
            {
                _logger.LogDebug($"Uploading large file: {x} bytes of {fileStream.Length} bytes already uploaded.");
            });

            UploadResult<DriveItem> uploadResult = await largeFileUpload.UploadAsync(progress);

            resultDriveItem = uploadResult.ItemResponse;
        }

        return resultDriveItem;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM