【问题标题】:Putting an image and variables in an HTTP Post (Not using FileUpload Control)将图像和变量放入 HTTP Post(不使用 FileUpload 控件)
【发布时间】:2013-10-30 01:21:36
【问题描述】:

继续我的帖子..

Saving an image from HTTP POST (Not using FileUpload Control)。我有点假设我可以使用 Request.Files..

为了测试保存功能,我现在正在研究通过 HTTP Post 发送图像,方法是在后面的代码中动态制作此 HTTP Post,并且不使用 FileUpload 控件强>。

这里涉及到了..

Send a file via HTTP POST with C#

但是,我正在寻找一个更完整的示例,并且可以确保维护其他 POST 变量。

事实上,这个可能会有所帮助..

Multipart forms from C# client

更新: 对不起..问题是..

如何通过 HTTP Post(无文件上传控制)连同其他 POST 变量将图像发送到 url,并让 Request.Files 在目标 url 中提取它?

解决方案

最后我在这里使用 WebHelpers 类解决了这个问题

Multipart forms from C# client

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    对于遇到此问题的任何人,使用 .NET 4.5(或 .NET 4.0,通过从 NuGet 添加 Microsoft.Net.Http 包)的更现代方法是使用 Microsoft.Net.Http。这是一个例子:

    private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
    {
        HttpContent stringContent = new StringContent(paramString);
        HttpContent fileStreamContent = new StreamContent(paramFileStream);
        HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
        using (var client = new HttpClient())
        using (var formData = new MultipartFormDataContent())
        {
            formData.Add(stringContent, "param1", "param1");
            formData.Add(fileStreamContent, "file1", "file1");
            formData.Add(bytesContent, "file2", "file2");
            var response = client.PostAsync(actionUrl, formData).Result;
            if (!response.IsSuccessStatusCode)
            {
                return null;
            }
            return response.Content.ReadAsStreamAsync().Result;
        }
    }
    

    【讨论】:

      【解决方案2】:

      我使用以下代码:

      用法

      List<IPostDataField> Fields = new List<IPostDataField>();
      Fields.Add(new PostDataField() { Name="nameOfTheField", Value="value" }); //simple field
      Fields.Add(new PostDataFile() { Name="nameOfTheField", FileName="something.ext", Content = byte[], Type = "mimetype" });
      
      string response = WebrequestManager.PostMultipartRequest(
          new PostDataEntities.PostData()
          {
              Fields = Fields
          }
          ,
                  "url");
      

      PostMultiPartRequest

          public static string PostMultipartRequest(PostData postData, string relativeUrl, IUserCredential userCredential)
          {
              string returnXmlString = "";
      
              try
              {
                  //Initialisatie request
                  WebRequest webRequest = HttpWebRequest.Create(string.Format(Settings.Default.Api_baseurl, relativeUrl));
                  //Credentials
                  NetworkCredential apiCredentials = userCredential.NetworkCredentials;
                  webRequest.Credentials = apiCredentials;
                  webRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(apiCredentials.UserName + ":" + apiCredentials.Password)));
                  //Post!
                  webRequest.Method = "POST";
                  webRequest.ContentType = "multipart/form-data; boundary=";
      
                  //Post
                  //byte[] bytesToWrite = UTF8Encoding.UTF8.GetBytes(multipartData);
                  string boundary = "";
                  byte[] data = postData.Export(out boundary);
                  webRequest.ContentType += boundary;
                  webRequest.ContentLength = data.Length;
                  using (Stream xmlStream = webRequest.GetRequestStream())
                  {
                      xmlStream.Write(data, 0, data.Length);
                  }
      
                  //webRequest.ContentType = "application/x-www-form-urlencoded";
                  using (WebResponse response = webRequest.GetResponse())
                  {
                      // Display the status
                      // requestStatus = ((HttpWebResponse)response).StatusDescription;
      
                      //Plaats 'response' in stream
                      using (Stream xmlResponseStream = response.GetResponseStream())
                      {
                          //Gebruik streamreader om stream uit te lezen en om te zetten naar string
                          using (StreamReader reader = new StreamReader(xmlResponseStream))
                          {
                              returnXmlString = reader.ReadToEnd();
                          }
                      }
                  }
              }
              catch (WebException wexc)
              {
                  switch (wexc.Status)
                  {
                      case WebExceptionStatus.Success:
                      case WebExceptionStatus.ProtocolError:
                          log.Debug("bla", wexc);
                          break;
                      default:
                          log.Warn("bla", wexc);
                          break;
                  }
              }
              catch (Exception exc)
              {
                  log.Error("bla");
              }
      
              return returnXmlString;
      
          }
      

      IPostdataField

      public interface IPostDataField
      {
         byte[] Export();
      }
      

      PostDataField

      public class PostDataField : IPostDataField
      {
          public string Name { get; set; }
          public string Value { get; set; }
      
          #region IPostDataField Members
      
          public byte[] Export()
          {
              using (MemoryStream stream = new MemoryStream())
              {
                  StreamWriter sw = new StreamWriter(stream);
                  {
                      StringBuilder sb = new StringBuilder();
                      sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", Name));
                      sb.AppendLine();
                      sb.AppendLine(Value);
                      sw.Write(sb.ToString());
                      sw.Flush();
                  }
      
                  stream.Position = 0;
      
                  byte[] buffer = new byte[stream.Length];
                  stream.Read(buffer, 0, (int)buffer.Length);
                  return buffer;
              }
          }
      
          #endregion
      }
      

      后数据文件

      public class PostDataFile : IPostDataField
      {
          public Byte[] Content { get; set; }
          public string Name { get; set; }
          public string FileName { get; set; }
          public string Type { get; set; } // mime type
      
          public byte[] Export()
          {
              using (MemoryStream stream = new MemoryStream())
              {
                  StreamWriter sw = new StreamWriter(stream);
      
                  StringBuilder sb = new StringBuilder();
                  sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", Name, FileName));
                  sb.AppendLine("Content-Type: " + Type);
                  sb.AppendLine();
      
                  sw.Write(sb.ToString());
      
                  sw.Flush();
      
                  stream.Write(Content, 0, Content.Length);
      
                  stream.Position = 0;
      
                  byte[] buffer = new byte[stream.Length];
                  stream.Read(buffer, 0, (int)buffer.Length);
                  return buffer;
              }
          }
      }
      

      邮政数据

      public class PostData
      {
          public PostData() { Fields = new List<IPostDataField>(); }
      
          public List<IPostDataField> Fields { get; set; }
      
          public Byte[] Export(out string boundary)
          {
              using (MemoryStream stream = new MemoryStream())
              {
                  Random r = new Random();
                  string tok = "";
                  for (int i = 0; i < 14; i++)
                      tok += r.Next(10).ToString();
      
                  boundary = "---------------------------" + tok;
                  using (StreamWriter sw = new StreamWriter(stream))
                  {
                      //sw.WriteLine(string.Format("Content-Type: multipart/form-data; boundary=" + boundary.Replace("--", "")));
                      //sw.WriteLine();
                      //sw.Flush();
      
                      foreach (IPostDataField field in Fields)
                      {
                          sw.WriteLine("--" + boundary);
                          sw.Flush();
      
                          stream.Write(field.Export(), 0, (int)field.Export().Length);
                      }
      
                      //1 keer om het af te leren
                      //sw.WriteLine();
                      sw.WriteLine("--" + boundary + "--");
                      sw.Flush();
      
                      stream.Position = 0;
      
                      using (StreamReader sr = new StreamReader(stream))
                      {
                          string bla = sr.ReadToEnd();
      
                          stream.Position = 0;
                          Byte[] toExport = new Byte[stream.Length];
                          stream.Read(toExport, 0, (int)stream.Length);
                          return toExport;
                      }
      
                  }
              }
          }
      }
      

      【讨论】:

      • 干杯 Jan,我会尝试你的建议。 ——李
      【解决方案3】:

      解决方案

      最后我在这里使用 WebHelpers 类解决了这个问题

      Multipart forms from C# client

      工作是一种享受。

      --李

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-30
        • 2016-02-02
        • 1970-01-01
        • 2016-06-20
        • 1970-01-01
        • 2021-10-10
        • 2014-08-30
        • 1970-01-01
        相关资源
        最近更新 更多