I have an HTTP server that supports multipart form upload of files. The working curl request looks like
curl -v --location --request POST 'http://192.168.1.3:9876/storage/module' \
--form 'name="I0000000001"' \
--form 'type="Log"' \
--form 'version="1.0.0.1"' \
--form 'user="admin"' \
--form 'file=@"/tmp/logDump.tgz"'
But I'm not able to convert this to C# successfully. The server is throwing HTTP 500 since the parameters (name
, version
, type
, and user
) are missing when sending with C#. I'm able to make this same file upload work in Curl, Python and C , so it is not an issue with the server, but with my C# code.
string filePath = @"/tmp/logDump.tgz";
using (var httpClient = new HttpClient())
{
using (var form = new MultipartFormDataContent())
{
using (var fs = File.OpenRead(filePath))
{
using (var streamContent = new StreamContent(fs))
{
using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()))
{
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(fileContent, "file", Path.GetFileName(filePath));
form.Add(new System.Net.Http.MultipartContent("SIM00000001"), "name");
form.Add(new System.Net.Http.MultipartContent("Log"), "type");
form.Add(new System.Net.Http.MultipartContent("1.0.0.135"), "version");
form.Add(new System.Net.Http.MultipartContent("admin"), "user");
HttpResponseMessage response = await httpClient.PostAsync("http://192.168.1.3:9876/storage/module", form);
response.EnsureSuccessStatusCode();
Console.WriteLine($" result is {response.StatusCode}");
}
}
}
}
}
How to do this correctly?
CodePudding user response:
The multipart form data should be sent as just key-value pairs, replace the below lines,
form.Add(new System.Net.Http.MultipartContent("SIM00000001"), "name");
...
to,
form.Add(new StringContent("SIM00000001"), "name");
...