WP8使用multipart / form-data在服务器上上传图像,收到错误

时间:2014-01-13 18:22:39

标签: windows-phone-8 multipartform-data dotnet-httpclient

以下代码尝试使用 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)

这是怎么做到的?

1 个答案:

答案 0 :(得分:4)

我找到了解决方案。

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);
            }
        }