添加文件以将数据发布到页面

时间:2010-02-18 20:23:05

标签: file post httpwebrequest

我有Windows应用程序,我想将数据发布到Url以从Web服务获取信息 这是我使用的代码:

 private string PostData(string url, string postData)
 {
      HttpWebRequest request = null;
      if (m_type == PostTypeEnum.Post)
      {
           Uri uri = new Uri(url);
           request = (HttpWebRequest)WebRequest.Create(uri);
           request.Method = "POST";
           request.ContentType = "application/x-www-form-urlencoded";
           request.ContentLength = postData.Length;

           using (Stream writeStream = request.GetRequestStream())
           {
                UTF8Encoding encoding = new UTF8Encoding();
                byte[] bytes = encoding.GetBytes(postData);
                writeStream.Write(bytes, 0, bytes.Length);
           }
      }
      else
      {
           Uri uri = new Uri(url + "?" + postData);
           request = (HttpWebRequest)WebRequest.Create(uri);
           request.Method = "GET";
      }

      string result = string.Empty;
      using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
      {
           using (Stream responseStream = response.GetResponseStream())
           {
                using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
                {
                     result = readStream.ReadToEnd();
                }
           }
      }
      return result;
 }

如何将文件添加到帖子数据?
我需要将文件发送到页面。

请问任何样品?

提前致谢,问候

1 个答案:

答案 0 :(得分:1)

您希望将ContentType更改为“multipart / form-data”,然后HTTP请求的正文将变为一系列MIME块,每个块包含您传递的数据的不同元素。

以下是formatting the multipart/form-data的W3C规范。