I was using the following code to send fromData contains 2 values (File and String) to a WebAPI using javascript.
var formData = new FormData();
formData.append('name', 'previewImg');
formData.append('upload', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'WebAPI url',
data: formData,
contentType: false,
processData: false,
// ... Other options like success and etc
})
I want to do the same thing using C# Windows Application, I need to write a Method accepts 2 paramters (FilePath and String) then send the file and the string to WebAPI.
I tried the following code but it returns an error from the service( I am trying to contact with koemei upload service) , although it works fine when I call it from Js :
void SendData(string filepath,string name){
var url = "URL";
HttpContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filepath));
using (var client = new HttpClient())
{
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, "upload");
formData.Add(new StringContent(name), "name");
//call service
var response = client.PostAsync(url, formData).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception();
}
else
{
if (response.Content.GetType() != typeof(System.Net.Http.StreamContent))
throw new Exception();
var stream = response.Content.ReadAsStreamAsync();
var content = stream.Result;
var path = @"name.txt";
using (var fileStream = System.IO.File.Create(path))
{
content.CopyTo(fileStream);
}
}
}
}
}