以下代码尝试使用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);
}
}
但是出现 HTTP 错误:(状态码 404,Http.StramContent,Header:Content-length=0)
如何正确地做到这一点?
最佳答案
我找到了解决方案。
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);
}
}
关于windows-phone-8 - WP8 使用 multipart/form-data 在服务器上上传图片,出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21098555/