当前位置:   article > 正文

C#、python企业微信群机器人自动发送文件_c# 腾讯企业微信群机器人 上传文件

c# 腾讯企业微信群机器人 上传文件
  1. 基本HTTP POST发送方式

  • 表单提交协议规定:
    要先将 HTTP 要求的 Content-Type 设为 multipart/form-data,而且要设定一个 boundary 参数,
    这个参数是由应用程序自行产生,它会用来识别每一份资料的边界 (boundary),
    用以产生多重信息部份 (message part)。
    而 HTTP 服务器可以抓取 HTTP POST 的信息,
    基本内容:
    1. 每个信息部份都要用 --[BOUNDARY_NAME] 来包装,以分隔出信息的每个部份,而最后要再加上一个 --[BOUNDARY_NAME] 来表示结束。
    2. 每个信息部份都要有一个 Content-Disposition: form-data; name="",而 name 设定的就是 HTTP POST 的键值 (key)。
    3. 声明区和值区中间要隔两个新行符号(\r\n)。
    4. 中间可以夹入二进制资料,但二进制资料必须要格式化为二进制字符串。
    5. 若要设定不同信息段的资料型别 (Content-Type),则要在信息段内的声明区设定。

  • 因此两个form内容模板为
    boundary = "----" + DateTime.Now.Ticks.ToString("x");//程序生成
    1.文本内容
    "\r\n--" + boundary +
    "\r\nContent-Disposition: form-data; name=\"键\"; filename=\"文件名\"" +
    "\r\nContent-Type: application/octet-stream" +
    "\r\n\r\n";
    2.文件内容
    "\r\n--" + boundary +
    "\r\nContent-Disposition: form-data; name=\"键\"" +
    "\r\n\r\n内容";

  • Python方法

  1. def upload_file(file_path, wx_upload_url):
  2. file_name = file_path.split("/")[-1]
  3. with open(file_path, 'rb') as f:
  4. length = os.path.getsize(file_path)
  5. data = f.read()
  6. headers = {"Content-Type": "application/octet-stream"}
  7. params = {
  8. "filename": file_name,
  9. "filelength": length,
  10. }
  11. file_data = copy(params)
  12. file_data['file'] = (file_path.split('/')[-1:][0], data)
  13. encode_data = encode_multipart_formdata(file_data)
  14. file_data = encode_data[0]
  15. headers['Content-Type'] = encode_data[1]
  16. print(headers)
  17. r = requests.post(wx_upload_url, data=file_data, headers=headers)
  18. print(r.text)
  19. media_id = r.json()['media_id']
  20. return media_id
  21. # media_id 通过上一步上传的方法获得
  22. def qi_ye_wei_xin_file(wx_url, media_id):
  23. headers = {"Content-Type": "text/plain"}
  24. data = {
  25. "msgtype": "file",
  26. "file": {
  27. "media_id": media_id
  28. }
  29. }
  30. r = requests.post(
  31. url=wx_url,
  32. headers=headers, json=data)
  • C#实现方式

    1. class FormItemModel
    2. {
    3. /// <summary>
    4. /// 表单键,request["key"]
    5. /// </summary>
    6. public string Key { set; get; }
    7. /// <summary>
    8. /// 表单值,上传文件时忽略,request["key"].value
    9. /// </summary>
    10. public string Value { set; get; }
    11. /// <summary>
    12. /// 是否是文件
    13. /// </summary>
    14. public bool IsFile
    15. {
    16. get
    17. {
    18. if (FileContent == null || FileContent.Length == 0)
    19. return false;
    20. if (FileContent != null && FileContent.Length > 0 && string.IsNullOrWhiteSpace(FileName))
    21. throw new Exception("上传文件时 FileName 属性值不能为空");
    22. return true;
    23. }
    24. }
    25. /// <summary>
    26. /// 上传的文件名
    27. /// </summary>
    28. public string FileName { set; get; }
    29. /// <summary>
    30. /// 上传的文件内容
    31. /// </summary>
    32. public byte[] FileContent { set; get; }
    33. }
    34. public static string PostForm(string url, List<FormItemModel> formItems, CookieContainer cookieContainer = null, string refererUrl = null, Encoding encoding = null, int timeOut = 20000)
    35. {
    36. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    37. #region 初始化请求对象
    38. request.Method = "POST";
    39. request.Timeout = timeOut;
    40. request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
    41. request.KeepAlive = true;
    42. request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
    43. if (!string.IsNullOrEmpty(refererUrl))
    44. request.Referer = refererUrl;
    45. if (cookieContainer != null)
    46. request.CookieContainer = cookieContainer;
    47. #endregion
    48. string boundary = "----" + DateTime.Now.Ticks.ToString("x");//分隔符
    49. request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
    50. //请求流
    51. var postStream = new MemoryStream();
    52. #region 处理Form表单请求内容
    53. //是否用Form上传文件
    54. var formUploadFile = formItems != null && formItems.Count > 0;
    55. if (formUploadFile)
    56. {
    57. //文件数据模板
    58. string fileFormdataTemplate =
    59. "\r\n--" + boundary +
    60. "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
    61. "\r\nContent-Type: application/octet-stream" +
    62. "\r\n\r\n";
    63. //文本数据模板
    64. string dataFormdataTemplate =
    65. "\r\n--" + boundary +
    66. "\r\nContent-Disposition: form-data; name=\"{0}\"" +
    67. "\r\n\r\n{1}";
    68. foreach (var item in formItems)
    69. {
    70. string formdata = null;
    71. if (item.IsFile)
    72. {
    73. //上传文件
    74. formdata = string.Format(
    75. fileFormdataTemplate,
    76. item.Key, //表单键
    77. item.FileName);
    78. }
    79. else
    80. {
    81. //上传键值对
    82. formdata = string.Format(
    83. dataFormdataTemplate,
    84. item.Key,
    85. item.Value);
    86. }
    87. //统一处理
    88. byte[] formdataBytes = null;
    89. //第一行不需要换行
    90. if (postStream.Length == 0)
    91. formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));
    92. else
    93. formdataBytes = Encoding.UTF8.GetBytes(formdata);
    94. postStream.Write(formdataBytes, 0, formdataBytes.Length);
    95. //写入文件内容
    96. if (item.FileContent != null && item.FileContent.Length > 0)
    97. {
    98. postStream.Write(item.FileContent, 0, item.FileContent.Length);
    99. }
    100. }
    101. //结尾
    102. var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
    103. postStream.Write(footer, 0, footer.Length);
    104. }
    105. else
    106. {
    107. request.ContentType = "application/x-www-form-urlencoded";
    108. }
    109. #endregion
    110. request.ContentLength = postStream.Length;
    111. #region 输入二进制流
    112. if (postStream != null)
    113. {
    114. postStream.Position = 0;
    115. //直接写入流
    116. Stream requestStream = request.GetRequestStream();
    117. byte[] buffer = new byte[1024];
    118. int bytesRead = 0;
    119. while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
    120. {
    121. requestStream.Write(buffer, 0, bytesRead);
    122. }
    123. postStream.Close();//关闭文件访问
    124. }
    125. #endregion
    126. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    127. if (cookieContainer != null)
    128. {
    129. response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
    130. }
    131. using (Stream responseStream = response.GetResponseStream())
    132. {
    133. using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8))
    134. {
    135. string retString = myStreamReader.ReadToEnd();
    136. return retString;
    137. }
    138. }
    139. }
    140. public static string Send_file(string Url, string media_id)
    141. {
    142. HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(Url);
    143. req.Method = "POST";
    144. req.ContentType = "application/octet-stream";//设置对应的ContentType
    145. string postdata = "{\"msgtype\": \"file\",\"file\": {\"media_id\":\""+ media_id+"\"}}";
    146. byte[] data = Encoding.UTF8.GetBytes(postdata);//把字符串转换为字节
    147. Stream writer = req.GetRequestStream();//获取
    148. writer.Write(data, 0, data.Length);
    149. writer.Flush();
    150. HttpWebResponse response = (HttpWebResponse)req.GetResponse();//获取服务器返回的结果
    151. Stream getStream = response.GetResponseStream();
    152. StreamReader streamreader = new StreamReader(getStream);
    153. String result = streamreader.ReadToEnd();
    154. return result;
    155. }

  • 上传文档成功截图

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/178454
推荐阅读
相关标签
  

闽ICP备14008679号