I am having a .pdf and .xml files which needs to be uploaded to an API at once (It means when I call an API, I need to upload these two files at the same time) from windows forms C# application.
Right now, I am looping in a for loop. So after uploading .pdf again in the loop it uploading .xml
Can anyone look into my code and tell me how can I upload two files in a single call?
private void button1_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
var dialogResult = openFileDialog1.ShowDialog();
if (dialogResult != DialogResult.OK) return;
string filecontent = "";
using (StreamReader reader = new StreamReader(openFileDialog1.OpenFile()))
{
filecontent = reader.ReadToEnd();
}
string filename = openFileDialog1.FileName;
string[] filenames = openFileDialog1.FileNames;
for (int i = 0; i < filenames.Count(); i++)
{
UploadFilesAsync(filenames[i]);
}
}
public static async Task<bool> UploadFilesAsync(params string[] paths)
{
HttpClient client = new HttpClient();
var multiForm = new MultipartFormDataContent();
foreach (string path in paths)
{
// add file and directly upload it
FileStream fs = File.OpenRead(path);
var streamContent = new StreamContent(fs);
//string dd = MimeType(path);
var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync());
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
multiForm.Add(fileContent, "files", Path.GetFileName(path));
}
var url = "https://spaysaas-dev.smartdocs.ai/api/getOCRDocuments";
using (var response = await client.PostAsync(url, multiForm))
{
return response.IsSuccessStatusCode;
if(response.IsSuccessStatusCode)
{
MessageBox.Show("Suucessfully uploaded the file to Server");
}
else
{
MessageBox.Show("Issues in your code, Please Check...!!!");
}
}
}