How to make a POST with "Multipart/form-data" using C# in Console applications?

Asked

Viewed 815 times

-1

I’m trying to do it like this and it’s not working:

var content = new MultipartFormDataContent();
httpClient.BaseAddress = new Uri(urlFinal);

var fileContent = new ByteArrayContent(File.ReadAllBytes(path));

fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "answer"
};

content.Add(fileContent);

var result = httpClient.PostAsync("file/upload", content).Result;

Console.WriteLine("Status: " + result.StatusCode);

1 answer

0

I tidied up your code, look how it turned out:

using (var client = new HttpClient())
{
    var fileContent = new ByteArrayContent(File.ReadAllBytes(path));
    using (var content = new MultipartFormDataContent("Upload"))
    {
        content.Add(fileContent);

        var result = client.PostAsync("file/upload", content).Result;

        using (var message = client.PostAsync("file/upload", content).Result)
        {
            var response = message.Content.ReadAsByteArrayAsync().Result;

            Console.WriteLine("Status: " + result.StatusCode);
        }
    }
}

Some remarks:

  • is using async methods synchronously and expecting the Result, try to turn your method into async and use await in async operations (for example await client.PostAsync("file/upload", content).

  • not seen in your code, but some objects are Disposable, that is, they can be using within a block of code using, like the HttpClient, that will release the resources once the using block is closed. If you don’t know how it works, search right here on the site has several questions and answers on the subject.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.