问题描述
尝试将文件上传到尚不存在的 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 });
}
}
推荐答案
我建议使用 ChunkedUploadProvider
实用程序.除了更容易使用之外,它还允许您上传任何方面的文件,而不是仅限于 4MB 以下的文件.
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.
您可以在 ChunkedUploadProvider 的示例.Graph.Test/Requests/Functional/OneDriveTests.cs#L39" rel="noreferrer">OneDriveUploadLargeFile
单元测试.
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 graph c# asp.net 将新文件上传到 onedrive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!