![](/img/trans.png)
[英]How to upload more than 4MB in c# using Microsoft Graph API rest calls
[英]How to upload a large document in c# using the Microsoft Graph API rest calls
我正在使用外部 .Net Web 應用程序,想知道如何使用 Microsoft Graph 將大文件上傳到文檔庫。 我最多可以上傳 4mb,但高於它的任何內容都會引發錯誤。
我知道有一個createUploadSession
但不知道如何實現它。 任何幫助將不勝感激。
這是我為成功上傳高達 4mb 所做的工作:
string requestUrl =
"https://graph.microsoft.com/v1.0/drives/{mydriveid}/items/root:/" +
fileName + ":/content";
HttpClient Hclient = new HttpClient();
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Put, requestUrl);
message.Content = new StreamContent(file.InputStream);
client.DefaultRequestHeaders
.TryAddWithoutValidation("Content-Type",
"application/json; odata=verbose; charset=utf-8");
HttpResponseMessage Hresponse = await client.SendAsync(message);
//if the response is 200 then read the response and retrive the GUID!
if (Hresponse.IsSuccessStatusCode)
{
responseString = await
Hresponse.Content.ReadAsStringAsync();
JObject jDataRetrieved = JObject.Parse(responseString);
strGuid = jDataRetrieved.SelectToken("eTag").ToString();
}
您可以使用客戶端庫來幫助您執行此操作。 從這個測試:
System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
var buff = (byte[])converter.ConvertTo(Microsoft.Graph.Test.Properties.Resources.hamilton, typeof(byte[]));
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(buff))
{
// Get the provider.
// POST /v1.0/drive/items/01KGPRHTV6Y2GOVW7725BZO354PWSELRRZ:/_hamiltion.png:/microsoft.graph.createUploadSession
// The CreateUploadSesssion action doesn't seem to support the options stated in the metadata.
var uploadSession = await graphClient.Drive.Items["01KGPRHTV6Y2GOVW7725BZO354PWSELRRZ"].ItemWithPath("_hamilton.png").CreateUploadSession().Request().PostAsync();
var maxChunkSize = 320 * 1024; // 320 KB - Change this to your chunk size. 5MB is the default.
var provider = new ChunkedUploadProvider(uploadSession, graphClient, ms, maxChunkSize);
// Setup the chunk request necessities
var chunkRequests = provider.GetUploadChunkRequests();
var readBuffer = new byte[maxChunkSize];
var trackedExceptions = new List<Exception>();
DriveItem itemResult = null;
//upload the chunks
foreach (var request in chunkRequests)
{
// Do your updates here: update progress bar, etc.
// ...
// Send chunk request
var result = await provider.GetChunkRequestResponseAsync(request, readBuffer, trackedExceptions);
if (result.UploadSucceeded)
{
itemResult = result.ItemResponse;
}
}
// Check that upload succeeded
if (itemResult == null)
{
// Retry the upload
// ...
}
}
創建上傳會話
// Create upload session
// POST /v1.0/drive/items/01KGPRHTV6Y2GOVW7725BZO354PWSELRRZ:/SWEBOKv3.pdf:/microsoft.graph.createUploadSession
var uploadSession = await graphClient.Drive.Items[itemId].ItemWithPath("SWEBOK.pdf").CreateUploadSession().Request().PostAsync();
創建任務
// Create task
var maxChunkSize = 320 * 1024; // 320 KB - Change this to your chunk size. 5MB is the default.
var largeFileUpload = new LargeFileUpload(uploadSession, graphClient, stream, maxChunkSize);
創建上傳監視器
public class MyProgress : IProgressCallback
{
public void OnFailure(ClientException clientException)
{
Console.WriteLine(clientException.Message);
}
public void OnSuccess(DriveItem result)
{
Console.WriteLine("Download completed with id below");
Console.WriteLine(result.Id);
}
public void UpdateProgress(long current, long max)
{
long percentage = (current * 100) / max ;
Console.WriteLine("Upload in progress. " + current + " bytes of " + max + "bytes. " + percentage + " percent complete");
}
}
上傳文件
uploadedFile = await largeFileUpload.ResumeAsync(new MyProgress());
創建上傳會話
// Create upload session
// POST /v1.0/drive/items/01KGPRHTV6Y2GOVW7725BZO354PWSELRRZ:/SWEBOKv3.pdf:/microsoft.graph.createUploadSession
string uri = $"https://graph.microsoft.com/v1.0/drive/items/{itemId}:/SWEBOKv3.pdf:/microsoft.graph.createUploadSession";
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uri);
await graphClient.AuthenticationProvider.AuthenticateRequestAsync(httpRequestMessage);
// Read the session info from the response
var httpResponseMessage = await graphClient.HttpProvider.SendAsync(httpRequestMessage);
var content = await httpResponseMessage.Content.ReadAsStringAsync();
var uploadSession = graphClient.HttpProvider.Serializer.DeserializeObject<UploadSession>(content);
創建任務
// Create task
var maxSliceSize = 320 * 1024; // 320 KB - Change this to your chunk size. 4MB is the default.
LargeFileUploadTask<DriveItem> largeFileUploadTask = new LargeFileUploadTask<DriveItem>(uploadSession, stream, maxSliceSize);
創建上傳監視器
// Setup the progress monitoring
IProgress<long> progress = new Progress<long>(progress =>
{
Console.WriteLine($"Uploaded {progress} bytes of {stream.Length} bytes");
});
上傳文件
UploadResult<DriveItem> uploadResult = null;
try
{
uploadResult = await largeFileUploadTask.UploadAsync(progress);
if (uploadResult.UploadSucceeded)
{
Console.WriteLine($"File Uploaded {uploadResult.ItemResponse.Id}");//Sucessful Upload
}
}
catch (ServiceException e)
{
Console.WriteLine(e.Message);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.