• HttpWebRequest上传多文件和多参数——整理


    1.整理HttpWebRequest上传多文件和多参数。较上一个版本,更具普适性和简易型。注意(服务方web.config中要配置)这样就可以上传大文件了

    <system.webServer>
          <requestFiltering>
            <requestLimits maxAllowedContentLength="4294967295" />
          </requestFiltering>
    </system.webServer>
    <system.web>
        <httpRuntime  maxRequestLength="2048000"/>
    </system.web>
    

    2.HttpWebRequest的封装

      /// <summary>
        /// Http上传文件类 - HttpWebRequest封装
        /// </summary>
        public class HttpUploadClient
        {
            public static string ExecuteMultipartRequest(string url, List<KeyValue> nvc)
            {
                string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                byte[] boundarybytes = Encoding.UTF8.GetBytes("
    --" + boundary + "
    ");
    
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url, UriKind.RelativeOrAbsolute));
                webRequest.Method = "POST";
                webRequest.Timeout = 1800000;
                webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                webRequest.KeepAlive = true;
                webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
                using (var rs = webRequest.GetRequestStream())
                {
                    // 普通参数模板
                    string formdataTemplate = "Content-Disposition: form-data; name="{0}"
    
    {1}";
                    //带文件的参数模板
                    string headerTemplate = "Content-Disposition: form-data; name="{0}"; filename="{1}"
    Content-Type: {2}
    
    ";
                    foreach (KeyValue keyValue in nvc)
                    {
                        //如果是普通参数
                        if (keyValue.FilePath == null)
                        {
                            rs.Write(boundarybytes, 0, boundarybytes.Length);
                            string formitem = string.Format(formdataTemplate, keyValue.Key, keyValue.Value);
                            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                            rs.Write(formitembytes, 0, formitembytes.Length);
                        }
                        //如果是文件参数,则上传文件
                        else
                        {
                            rs.Write(boundarybytes, 0, boundarybytes.Length);
                            string header = string.Format(headerTemplate, keyValue.Key, keyValue.Value, keyValue.ContentType);
                            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                            rs.Write(headerbytes, 0, headerbytes.Length);
                            using (var fileStream = new FileStream(keyValue.FilePath, FileMode.Open, FileAccess.Read))
                            {
                                byte[] buffer = new byte[4096];
                                int bytesRead = 0;
                                long total = 0;
                                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                {
                                    rs.Write(buffer, 0, bytesRead);
                                    total += bytesRead;
                                }
                            }
                        }
    
                    }
                    byte[] trailer = Encoding.UTF8.GetBytes("
    --" + boundary + "--
    ");
                    rs.Write(trailer, 0, trailer.Length);
                    rs.Close();
                }
    
                // 获取响应
                using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        string body = reader.ReadToEnd();
                        reader.Close();
                        return body;
                    }
                }
            }
    

    3.参数封装(支持普通参数和多文件)

      public class KeyValue
        {
            public string Key;
            public string Value;
            public string FilePath;
            public string ContentType = "*/*";
            public KeyValue(string key, string value, string filePath, string contentType)
            {
                Key = key;
                Value = value;
                FilePath = filePath;
                ContentType = contentType;
            }
            public KeyValue() { }
            public KeyValue(string key, string value, string filePath)
            {
                Key = key;
                Value = value;
                FilePath = filePath;
            }
            public KeyValue(string key, string value)
            {
                Key = key;
                Value = value;
            }
        }
    

    4.调用示例

                List<KeyValue> keyValues = new List<KeyValue>();
                keyValues.Add(new KeyValue("key1", "12_423232523"));
                keyValues.Add(new KeyValue("key2", " 1 2 3"));
                keyValues.Add(new KeyValue("file1", "1.img", @"C:临时	empDB1.img"));
                keyValues.Add(new KeyValue("file2", "2.xls", @"C:临时	empDB2.xls"));
                HttpUploadClient.ExecuteMultipartRequest(url, keyValues);
    

    5.服务接收方示例

      for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
      {
           HttpPostedFile file = HttpContext.Current.Request.Files[i];
           file.SaveAs(""+file.FileName);
      }
      string Params = HttpContext.Current.Request.Form["key1"];
    

      

  • 相关阅读:
    android xml 布局错误
    java int与integer的区别
    android html.fromHtml 用例
    Android 手势操作识别
    android android 判断是否滑动
    Android 通过 Intent 传递类对象或list对象
    android 学习JSON
    android 解决ListView点击与滑动事件冲突
    关于android的日志输出&LogCat
    android ListView 属性
  • 原文地址:https://www.cnblogs.com/xibei/p/6126277.html
Copyright © 2020-2023  润新知