Reputation: 163
Following code tries to upload image to server using multipart/form-data:
public async void PostRequest(Stream photoStream, string lomail, string fileName)
{
try
{
using (HttpClient client = new HttpClient())
{
client.Timeout = TimeSpan.FromMinutes(10);
photoStream.Position = 0;
using (MultipartFormDataContent content = new MultipartFormDataContent())
{
content.Add(new StringContent(lomail), "lomail");
content.Add(new StreamContent(photoStream), "photo", fileName);
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("post");
});
HttpResponseMessage response = await client.PostAsync(LoUrl, content);
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(response.ToString());
});
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("finish");
});
}
}
}
catch (Exception e)
{
MessageBox.Show("post request: " + e.Message);
}
}
But there's HTTP error: (status code 404, Http.StramContent, Header: Content-length=0)
How do this correctly?
Upvotes: 3
Views: 1332
Reputation: 163
I found the solution.
public async void PostRequest(Stream photoStream, string lomail, string fileName)
{
try
{
using (HttpClient client = new HttpClient())
{
client.Timeout = TimeSpan.FromMinutes(10);
photoStream.Position = 0;
using (MultipartFormDataContent content = new MultipartFormDataContent())
{
content.Add(new StringContent(lomail), "lomail");
content.Add(new StreamContent(photoStream), "photo", fileName);
//var imageContent = new ByteArrayContent(ImageData);
//imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
//content.Add(imageContent, "photo", "image.jpg");
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("post");
});
HttpResponseMessage response = await client.PostAsync(LoUrl, content);
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(response.ToString());
});
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("finish");
});
}
}
}
catch (Exception e)
{
MessageBox.Show("post request: " + e.Message);
}
}
Upvotes: 4