本片主要解决“type=file时是可行的,type=image时不知为何总是提示【系统繁忙】”的问题。
钉钉上传素材的API文档写的比较简单,尤其是http头那块完全没写,demo也没有.net的,杯具啊。
看了一位仁兄的帖子,原理写的很清楚,大家可以参考一下。
http://blog.csdn.net/xxdddail/article/details/51983487
但有一个问题没有解决,文章里也提到了,就是type=file时是可行的,type=image时不知为何总是提示【系统繁忙】
研究了好几天,参考了下面这位仁兄的代码
https://github.com/icodegame/DTSigninRemind
终于找到了问题,貌似是C#提供的WebClient的问题,改用HttpWebRequest解决了。
在自定义头一样的情况下WebClient不行,但HttpWebRequest可以。
想了解http头的话,请看这一篇,http://blog.csdn.net/xiaojianpitt/article/details/6856536
上面github上的仁兄代码是异步的,我需要同步方式,就直接改成同步的了。如果需要异步的代码可以用上面链接里的代码。
代码如下
1 public static string PostFile(string url, string fileWithPath)
2 {
3 var result = string.Empty;
4 var request = (HttpWebRequest)WebRequest.Create(url);
5 var boundary = "----------" + DateTime.Now.Ticks.ToString("x");
6 request.ContentType = "multipart/form-data; boundary=" + boundary;
7 request.Method = "POST";
8 using (Stream requestStream = request.GetRequestStream())
9 {
10 byte[] boundarybytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
11 byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "–-\r\n");
12 var filename = Path.GetFileName(fileWithPath);
13 using (FileStream fs = new FileStream(fileWithPath, FileMode.Open, FileAccess.Read))
14 {
15 byte[] bArr = new byte[fs.Length];
16 fs.Read(bArr, 0, bArr.Length);
17 requestStream.Write(boundarybytes, 0, boundarybytes.Length);
18 var header = $"Content-Disposition:form-data;name=\"media\";filename=\"{filename}\"\r\nfilelength=\"{fs.Length}\"\r\nContent-Type:application/octet-stream\r\n\r\n";
19 byte[] postHeaderBytes = Encoding.UTF8.GetBytes(header.ToString());
20 requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
21 fs.Close();
22 requestStream.Write(bArr, 0, bArr.Length);
23 requestStream.Write(trailer, 0, trailer.Length);
24 }
25 }
26 var response = (HttpWebResponse)request.GetResponse();
27 var responseStream = response.GetResponseStream();
28 using (var streamReader = new StreamReader(response.GetResponseStream()))
29 {
30 result = streamReader.ReadToEnd();
31 }
32 return result;
33 }
调用代码
1 var fileName = @"d:\a.jpg";
2 var url = $"https://oapi.dingtalk.com/media/upload?access_token={access_token}&type=image";
3 var requestResult = PostFile(url, fileName);
返回的结果
|