Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I use te POSTMAN application to upload a file to an API,
now I want to actually do a POST commando in c#, how can I do this in the most efficient way?

url "192.168.0.1/api/files"

Header
key= Authorization, value = "123456"

Formdata
key= files, value = <file>
key= Info, value = <{"DocName": "Test"}>

if status == 200
Console.WriteLine("OK");
else
Console.WriteLine( "ERROR" + response.StatusCode + " : Message - " + response.ReasonPhrase);

What I have tried:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https:///api.ontriz.com/files");
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "123456");

but then??
Posted
Updated 18-Jan-17 9:06am
v2
Comments
F-ES Sitecore 18-Jan-17 6:26am    
Google "c# post file web api" and I'm sure you'll find the code
MaikelO1 18-Jan-17 8:11am    
thanks for your comment. not tried that but unfortunately with an error result

1 solution

Use the MultipartFormDataContent class[^]:
C#
using (var form = new MultipartFormDataContent())
using (var stream = File.OpenRead(@"Path\To\Your\File.ext"))
using (var streamContent = new StreamContent(stream))
{
    form.Add(streamContent, "files");
    form.Add(new StringContent("<{\"DocName\": \"Test\"}>"), "Info");
    response = await client.PostAsync(null, form);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900