Click here to Skip to main content
14,298,693 members
Rate this:
Please Sign up or sign in to vote.
Hi,

I would like to upload an image from my project to my web service.

How can I put the image into my PostAsync in order to upload to my PHP web service?


Thanks,
Jassim

What I have tried:

Here is my code:

byte[] fileBytes;

using (var fileStream = await imageEditor.GetStream())
{
    var binaryReader = new BinaryReader(fileStream);

    fileBytes = binaryReader.ReadBytes((int)fileStream.Length);
}

var imageBinaryContent = new ByteArrayContent(fileBytes);

var multipartContent = new MultipartFormDataContent();
multipartContent.Add(imageBinaryContent, "image");



and my PostAsync is like this:


var client = new HttpClient();
client.BaseAddress = new Uri("https://my.domain.com/api/save_data.php");

client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var content = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("image", IMAGE_DATA_COMES_HERE)
});

var response = await client.PostAsync("https://my.domain.com/api/save.php", content);
Posted
Updated 3 days ago

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

You can't use FormUrlEncodedContent to upload a file; you have to use MultipartFormDataContent.
var content = new MultipartFormDataContent();
var imageContent = new StreamContent(await imageEditor.GetStream());
content.Add(imageContent, "image");

var response = await client.PostAsync("https://my.domain.com/api/save.php", content);
   
Comments
Jassim Rahma 2 days ago
   
but I need to pass more than one parameter like this:

var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string="">("student", Convert.ToString(student_number)),
new KeyValuePair<string, string="">("photo", STUDENT_PHOTO),
});

so I should pass it as a string?
Richard Deeming 13hrs ago
   
You cannot use FormUrlEncodedContent to upload a file.
var content = new MultipartFormDataContent();

// Add the image:
var imageContent = new StreamContent(await imageEditor.GetStream());
content.Add(imageContent, "photo");

// Add another parameter:
content.Add(new StringContent(Convert.ToString(student_number)), "\"student\"");

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100