C# HttpPost 【ContentType:multipart/form-data】表单提交 file 类型数据方法 2

参考来源:https://blog.csdn.net/qq_39788123/article/details/128495546

 

try
{
  Dictionary<string, string> headerDict = new Dictionary<string, string>();
  NameValueCollection par = new NameValueCollection();
  //par.Add("dataSource", "数据源"); //数据源
  dynamic fileInfo = new ExpandoObject();
  fileInfo.fileName = "C:/Users/admin/Desktop/ico/A001.png"; //文件名
  byte[] fileByte = File.ReadAllBytes("C:/Users/admin/Desktop/ico/A001.png");
  fileInfo.fileByte = fileByte; //文件字节
  fileInfo.file = "file"; //字段名
  //请求
  string result = PostMultipartFormDataAsync("https://*******.co.th/**/getFileUrl", headerDict, par, fileInfo);
}
catch (System.Exception ex)
{
  Console.Write("SendThaiFormData Error:" + ex.Message);
}

 

/// <summary>
/// 使用multipart/form-data方式上传文件及其他数据
/// </summary>
/// <param name="requestUrl">请求接口地址</param>
/// <param name="headers">自定义header</param>
/// <param name="nameValueCollection">键值对参数</param>
/// <param name="fileInfo">文件信息</param>
/// <returns></returns>
public static string PostMultipartFormDataAsync(string requestUrl, Dictionary<string, string> headers, NameValueCollection nameValueCollection, dynamic fileInfo)
{
  var data = "";
  ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
    | SecurityProtocolType.Tls
    | SecurityProtocolType.Tls11
    | SecurityProtocolType.Tls12;
  using (var httpClient = new HttpClient())
  {
    try
    {

      //header参数
      foreach (var item in headers)
      {
        httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
      }

      using (var reduceAttach = new MultipartFormDataContent())
      {
        #region 键值对参数
        string[] allKeys = nameValueCollection.AllKeys;
        foreach (string key in allKeys)
        {
          var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(nameValueCollection[key]));
          dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
          {
            Name = key
          };
          reduceAttach.Add(dataContent);
        }
        #endregion

        #region 文件参数
        if (fileInfo != null)
        {
          Stream fileStream = new MemoryStream(fileInfo.fileByte); //转成stream流
          var streamContent = new StreamContent(fileStream);
          var Content = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);//创建文件的content
          reduceAttach.Add(Content, fileInfo.file, fileInfo.fileName);
          streamContent.Dispose();
        }
        #endregion

        //请求
        var response = httpClient.PostAsync(requestUrl, reduceAttach).Result;
        data = response.Content.ReadAsStringAsync().Result;
      }
    }
    catch (Exception ex)
    {
      throw ex;
    }
  }
  return data;
}

posted @ 2023-03-10 09:29  剑存古风  阅读(219)  评论(0编辑  收藏  举报