Skip to content

Instantly share code, notes, and snippets.

@akrisiun
Last active July 27, 2020 11:45
Show Gist options
  • Save akrisiun/b8d8408b37fd69b3badd43ffa3301c05 to your computer and use it in GitHub Desktop.
Save akrisiun/b8d8408b37fd69b3badd43ffa3301c05 to your computer and use it in GitHub Desktop.
UploadRequestAsync C# task

https://stackoverflow.com/questions/63062474/asynchrounous-chunked-file-upload-in-c-sharp

// Call to chunk and upload file in another async method. I'm only showing the call here:
FileStream fileStream = new FileStream(fileNameIn, FileMode.Open, FileAccess.Read);
await ChunkFileAsync(fileStream, uploadFile.Name, url);

UploadFile.cs

// To upload chunks to remote server
        public static async Task<bool> UploadRequestAsync(string fileName, string url, int loopCounter, Byte[] bytes)
        {
            bool response = false;
            try
            {

                ASCIIEncoding ascii = new ASCIIEncoding();
                ByteArrayContent data = new ByteArrayContent(bytes);
                data.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("multipart/form-data");
                byte[] strParamsBytes = ascii.GetBytes(strVals);
                HttpClient requestToServer = new HttpClient();
                MultipartFormDataContent form = new MultipartFormDataContent();
                form.Add(data, "file", fileName + loopCounter);
                await requestToServer.PostAsync(url, form);
                requestToServer.Dispose();
                response = true;

            }
            catch (Exception e)
            {
                Console.WriteLine("There was an exception: " + e);
            }
            return response;
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment