Upload heavy files to SharePoint Online - SharePoint REST API

Amit Singh Rawat 731 Reputation points
2023-09-12T15:23:53.03+00:00

Hi All,

I have some large files in my environment, exceeding 1GB in size, and I'm attempting to upload them to a SharePoint online site using the C# SharePoint REST API. However, I'm encountering an error message that says, "Connection forcibly closed by host" when I try to upload these files. The code works well with files less than 150MB.

Below is the relevant code. Could someone please confirm how to achieve this successfully?

static async Task PutUploadLargeFileAsync(string accessToken, string filePath, string sharePointUrl, string libraryName)
        {
            using HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
            client.Timeout = TimeSpan.FromMinutes(20);

            var fileStream = new FileStream(filePath, FileMode.Open);
            var fileName = Path.GetFileName(filePath);

            var requestUri = $"{sharePointUrl}/_api/web/lists/getbytitle('{libraryName}')/RootFolder/Files/Add(url='{fileName}', overwrite=true)";

            var response = await client.PutAsync(requestUri, new StreamContent(fileStream));

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("File uploaded successfully.");
            }
            else
            {
                Console.WriteLine($"File upload failed. Status code: {response.StatusCode}");
            }
        }
Microsoft 365 and Office SharePoint Development
Microsoft 365 and Office SharePoint For business Windows
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2023-09-13T06:32:24.5833333+00:00

    Hi @ASR

    You need to split the file in smaller parts see the example here:

    https://social.msdn.microsoft.com/Forums/en-US/191424a8-e94e-4512-b3db-f53fea7463e5/how-to-upload-a-big-file-in-mvc?forum=aspmvc


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards

    Cheng Feng


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.