如何使用 Microsoft Graph API rest calls 在 c# 中上传超过 4MB

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

我没有成功将超过 4MB 的文件上传到 OneDrive,我已成功创建文件夹、重命名、删除,甚至上传了 4MB 或更小的文件,但是上传超过 4MB 的文件似乎是一个稍微复杂一点。我一直试图通过查看此解决方案来理解 How to upload a large document in c# using the Microsoft Graph API rest calls

有两种解决方法。投票较高的解决方案建议使用冗长的方法(但是函数 "GetChunkRequestResponseAsync" 已被弃用,我一直无法找到合适的函数来执行相同的操作),第二个解决方案使用 "new LargeFileUpload",然而,当我把它放在我的代码中时(Visual Studio),它告诉我只有 "LargeFileUploadTask < ? > " 存在(外观相同的功能但是最后有一个 "Task"。我不明白什么放 "Task < string > ???".

无论如何,我绝对明白必须请求 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);

但如有任何帮助和建议,我们将不胜感激。如果这意味着什么,这里是 link 帮助我上传小于 4MB 的人: 谢谢

微软大大简化了大文件的上传,因为问题的帖子。我目前正在使用 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;
    }