Skip to content

Instantly share code, notes, and snippets.

@tocalai
Last active November 17, 2022 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tocalai/b23e1acf50d9e0409a24f5ee384b4555 to your computer and use it in GitHub Desktop.
Save tocalai/b23e1acf50d9e0409a24f5ee384b4555 to your computer and use it in GitHub Desktop.
// files: suppose we have a list of file paths
// subDirectory: the sub-directory structure under root for storing
public async Task<HttpResponseMessage> UploadFilesAsync(List<string> files, string subDirectory)
{
string boundary = $"--{DateTime.Now.Ticks:x}";
using var content = new MultipartFormDataContent(boundary);
content.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
foreach (var filePath in files)
{
content.Add(new StringContent(subDirectory, Encoding.UTF8), "subDirectory");
using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var fileNameHash = Path.GetFileNameWithoutExtension(filePath) + "_" + Guid.NewGuid().ToString("N") + Path.GetExtension(filePath);
content.Add(new StreamContent(stream), "files", fileNameHash);
}
// IHttpClientFactory, consider using factory would be more effeicecy
var httpClient = new HttpClient();
using HttpRequestMessage request = new(HttpMethod.Post, new Uri("{your file API uri}")) { Content = content };
// fire the post with the MultipartFormDataContent to File API
var result = await httpClient.SendAsync(request);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment