Search code examples
c#file-uploadmicrosoft-graph-apionedrivemicrosoft-graph-sdks

File path when uploading files through OneDrive SDK


Use the OneDrive SDK to upload files.

At this time, you have to pass the file path, but uploading using the code takes a long time.

Can I upload files even if I pass the temporary file path?

Currently I get the file path after saving the file to the server.

In this case, an issue arises from speed problems.

Is there any way to look at the temporary file path?

public async Task<JObject> UploadLargeFiles(string upn, IFormFile files)
    {
        var jObject = new JObject();
        int fileSize = Convert.ToInt32(files.Length);

        var folderName = Path.Combine("wwwroot", "saveLargeFiles");
        var pathToSave = Path.Combine(System.IO.Directory.GetCurrentDirectory(), folderName);
        var fullPath = "";

        if (files.Length > 0)
        {
            var fileName = files.FileName;
            fullPath = Path.Combine(pathToSave, fileName);

            using (var stream = new FileStream(fullPath, FileMode.Create))
                files.CopyTo(stream);
        }

        var filePath = fullPath;

        var fileStream = System.IO.File.OpenRead(filePath);
        GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient();

        var uploadProps = new DriveItemUploadableProperties
        {
            ODataType = null,
            AdditionalData = new Dictionary<string, object>
            {
                { "@microsoft.graph.conflictBehavior", "rename" }
            }
        };

        var item = this.SelectUploadFolderID(upn).Result;
        var uploadSession = await client.Users[upn].Drive.Items[item].ItemWithPath(files.FileName).CreateUploadSession(uploadProps).Request().PostAsync();

        int maxChunkSize = 320 * 1024;
        var uploadTask = new LargeFileUploadTask<DriveItem>(uploadSession, fileStream, maxChunkSize);

        var response = await uploadTask.UploadAsync();

        if (response.UploadSucceeded)
        {
            return 
        }
        else
        {
            return null;
        }
    }

Solution

  • Your server's disk is probably not what makes this slow. By default, uploaded files are stored in a temporary directory, which you can save permanently by using CopyTo(FileStream) like you do.

    You can skip this step and call IFormFile.OpenReadStream() to obtain a stream to the temporary file, then pass that to the LargeFileUploadTask.

    Point is, it's probably the uploading to OneDrive that takes the largest amount of time. Depending on your setup, you may want to save files into a queue directory (the temp file gets deleted after the request completes), and have a background service read that queue and upload them to OneDrive.