使用Microsoft图形C#ASP.NET将新文件上传到OneDrive [英] Upload new file to onedrive using microsoft graph c# asp.net

查看:69
本文介绍了使用Microsoft图形C#ASP.NET将新文件上传到OneDrive的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将文件上传到尚不存在的onedrive.我设法得到它来更新现有文件.但是似乎无法弄清楚如何创建一个全新的文件.我已经使用Microsoft.Graph库完成了此操作.

Trying to upload a file to onedrive that does not already exist. I have managed to get it to update an existing file. But can't seem to figure out how to create a brand new file. I have done this useing the Microsoft.Graph library.

以下是用于更新现有文件的代码:

Here is the code that works to update an existing file:

public async Task<ActionResult> OneDriveUpload()
    {
        string token = await GetAccessToken();
        if (string.IsNullOrEmpty(token))
        {
            // If there's no token in the session, redirect to Home
            return Redirect("/");
        }

        GraphServiceClient client = new GraphServiceClient(
            new DelegateAuthenticationProvider(
                (requestMessage) =>
                {
                    requestMessage.Headers.Authorization =
                        new AuthenticationHeaderValue("Bearer", token);

                    return Task.FromResult(0);
                }));


        try
        {
            string path = @"C:/Users/user/Desktop/testUpload.xlsx";
            byte[] data = System.IO.File.ReadAllBytes(path);
            Stream stream = new MemoryStream(data);
            // Line that updates the existing file             
            await client.Me.Drive.Items["55BBAC51A4E4017D!104"].Content.Request().PutAsync<DriveItem>(stream);

            return View("Index");
        }
        catch (ServiceException ex)
        {
            return RedirectToAction("Error", "Home", new { message = "ERROR retrieving messages", debug = ex.Message });
        }
    }

推荐答案

我建议使用

I'd suggest using the ChunkedUploadProvider utility that is included in the SDK. Aside from being a little easier to work with, it will allow you to upload files of any side rather than being limited to files under 4MB.

您可以在

You can find a sample of how to use ChunkedUploadProvider in the OneDriveUploadLargeFile unit test.

要回答您的直接问题,上传对于替换和创建文件都是相同的.但是,您确实需要指定文件名,而不只是现有的项目号:

To answer your direct question, uploading works the same for both replacing and creating files. You do however need to specify the file name rather than just an existing Item number:

await graphClient.Me
    .Drive
    .Root
    .ItemWithPath("fileName")
    .Content
    .Request()
    .PutAsync<DriveItem>(stream);

这篇关于使用Microsoft图形C#ASP.NET将新文件上传到OneDrive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆