Last active
November 17, 2022 08:14
-
-
Save tocalai/b23e1acf50d9e0409a24f5ee384b4555 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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