2

I am not very familiar with streams but googling got me some code but its not working. I want to upload a image to a server that accept a post in multipartform here is my code, its not working and i dont know if its correct or not. Please guide

 MemoryStream stream;
                            using ( stream = new MemoryStream())
                            {
                                using (var writer = new StreamWriter(stream))
                                {
                                    writer.Write("multipart/form-data; boundary=---------------------------" + ak);
                                    if (image_path1.ToLower().Contains("png"))
                                    {
                                        writer.Write("Content-Disposition: form-data;");
                                        writer.Write("name=img;");
                                        writer.Write("filename="+name+";");
                                        writer.Write("Content-Type: image/png");
                                    }
                                    else
                                    {
                                        writer.Write("Content-Disposition: form-data;");
                                        writer.Write("name=img;");
                                        writer.Write("filename=" + name + ";");
                                        writer.Write("Content-Type: image/jpeg");
                                    }
                                    writer.Flush();

                                    var file1 = File.ReadAllBytes(image_path1);
                                    stream.Write(file1, 0, file1.Length);
                                   // stream.Flush();
                                }
                            }

Next i dont even know how to post it, for normal post i using like this

string response = client.Post(domain, post_string);

I have to create request like this http://prntscr.com/1gje7l and functions are http://prntscr.com/1gjefr

4

1 回答 1

3

HttpClient具有PostAsync接受HttpContent对象的方法。

你可以像这样使用它:

using(var f = System.IO.File.OpenRead(@"F:\test.html"))
{
      var client = new HttpClient();
      var content = new StreamContent(f);
      var mpcontent = new MultipartFormDataContent();
      content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
      mpcontent.Add(content);   
      await client.PostAsync("http://ya.ru", mpcontent);
}

您无需手动管理标题、边界等

于 2013-07-20T18:33:12.903 回答