繁体   English   中英

使用 Microsoft Graph 将新文件上传到 onedrive c# asp.net

[英]Upload new file to onedrive using microsoft graph c# asp.net

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

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

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 });
        }
    }

我建议使用SDK中包含的ChunkedUploadProvider实用程序。 除了更容易使用之外,它还允许您上传任何一方的文件,而不仅限于4MB以下的文件。

您可以在OneDriveUploadLargeFile单元测试中找到如何使用ChunkedUploadProvider的示例。

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

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

此代码将帮助大家在 ASP.NEt Core 中使用 Microsoft graph Api Sdk 上传大小文件

上传或替换 DriveItem 的内容

*Controller code : -*      
  [BindProperty]
        public IFormFile UploadedFile { get; set; }
        public IDriveItemChildrenCollectionPage Files { get; private set; }

        public FilesController(ILogger<FilesModel> logger, GraphFilesClient graphFilesClient, GraphServiceClient graphServiceClient, ITokenAcquisition tokenAcquisition)
        {
            _graphFilesClient = graphFilesClient;
            _logger = logger;
            _graphServiceClient = graphServiceClient;
            _tokenAcquisition = tokenAcquisition;
        }


[EnableCors]
        [HttpPost]
        [Route("upload-file")]
        [RequestFormLimits(MultipartBodyLengthLimit = 100000000)]
        [RequestSizeLimit(100000000)]
        public async Task<IActionResult> uploadFiles(string itemId, string folderName, [FromHeader] string accessToken)
        {

            _logger.LogInformation("into controller");
            if (UploadedFile == null || UploadedFile.Length == 0)
            {
                return BadRequest();
            }

            _logger.LogInformation($"Uploading {UploadedFile.FileName}.");

            var filePath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), UploadedFile.FileName);
            _logger.LogInformation($"Uploaded file {filePath}");


            using (var stream = new MemoryStream())
            {

                UploadedFile.CopyTo(stream);
                var  bytes = stream.ToArray();
                _logger.LogInformation($"Stream {stream}.");
                stream.Flush();
                await _graphFilesClient.UploadFile(
                UploadedFile.FileName, new MemoryStream(bytes), itemId, folderName, accessToken);
            }

            return Ok("Upload Successful!");
        }

*Service code :-* 

 [EnableCors]
        public async Task UploadFile(string fileName, Stream stream,string itemId,string folderName,string accessToken)
        {

            GraphClients graphClients = new GraphClients(accessToken);
            GraphServiceClient _graphServiceClient = graphClients.getGraphClient();
            _logger.LogInformation("Into Service");

            var filePath = Path.Combine(System.IO.Directory.GetCurrentDirectory(),fileName);

            _logger.LogInformation($"filepath : {filePath}");

            Console.WriteLine("Uploading file: " + fileName);

            var size = stream.Length / 1000;
            _logger.LogInformation($"Stream size: {size} KB");
            if (size/1000 > 4)
            {
                // Allows slices of a large file to be uploaded 
                // Optional but supports progress and resume capabilities if needed
                await UploadLargeFile(filePath, stream,accessToken);
            }
            else
            {
                try
                {
                    _logger.LogInformation("Try block");

                    String test = folderName + "/" + fileName;
                    // Uploads entire file all at once. No support for reporting progress.
// for getting your sharepoint site open graph explorer > sharepoint sites > get my organization's default sharepoint site.


                    var driveItem = await _graphServiceClient
                        .Sites["Your share point site"]
                        .Drive
                        .Root.ItemWithPath(test)
                        .Content
                        .Request()
                        .PutAsync<DriveItem>(stream);
                    _logger.LogInformation($"Upload complete: {driveItem.Name}");
                }
                catch (ServiceException ex)
                {
                    _logger.LogError($"Error uploading: {ex.ToString()}");
                    throw;
                }
            }
        }


        private async Task UploadLargeFile(string itemPath, Stream stream,string accessToken)
        {
            GraphClients graphClients = new GraphClients(accessToken);
            GraphServiceClient _graphServiceClient = graphClients.getGraphClient();
            // Allows "slices" of a file to be uploaded.
            // This technique provides a way to capture the progress of the upload
            // and makes it possible to resume an upload using fileUploadTask.ResumeAsync(progress);
            // Based on https://docs.microsoft.com/en-us/graph/sdks/large-file-upload

            // Use uploadable properties to specify the conflict behavior (replace in this case).
            var uploadProps = new DriveItemUploadableProperties
            {
                ODataType = null,
                AdditionalData = new Dictionary<string, object>
                {
                    { "@microsoft.graph.conflictBehavior", "replace" }
                }
            };

            // Create the upload session
            var uploadSession = await _graphServiceClient.Me.Drive.Root
                                    .ItemWithPath(itemPath)
                                    .CreateUploadSession(uploadProps)
                                    .Request()
                                    .PostAsync();

            // Max slice size must be a multiple of 320 KiB
            int maxSliceSize = 320 * 1024;
            var fileUploadTask = new LargeFileUploadTask<DriveItem>(uploadSession, stream, maxSliceSize);

            // Create a callback that is invoked after
            // each slice is uploaded
            IProgress<long> progress = new Progress<long>(prog =>
            {
                _logger.LogInformation($"Uploaded {prog} bytes of {stream.Length} bytes");
            });

            try
            {
                // Upload the file
                var uploadResult = await fileUploadTask.UploadAsync(progress);

                if (uploadResult.UploadSucceeded)
                {
                    _logger.LogInformation($"Upload complete, item ID: {uploadResult.ItemResponse.Id}");
                }
                else
                {
                    _logger.LogInformation("Upload failed");
                }

            }
            catch (ServiceException ex)
            {
                _logger.LogError($"Error uploading: {ex.ToString()}");
                throw;
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM