. NET allows the WeChat public platform to upload and download multimedia files, and. net to upload and download

Source: Internet
Author: User
Tags cdata

. NET allows you to upload and download multimedia files on the public platform.

For example, someone sends a photo to our public account and then processes the photo, for example, ocr (which will be down to this example later) or face recognition, these functions are quite useful. Now we need to analyze this process. The Platform certainly cannot help us with OCR, face recognition, and other functions. To do these functions, we must first obtain the image! The user's photo was first uploaded to the wenxin server, and then a mediaID was created. We can use this mediaID to download it to our own server, process it, and send the result to the platform, the final feedback from the platform is provided to the users ). The development documentation has provided a way to download resources. I transformed it to. net, as shown below:

/// <SUMMARY> /// download and save the multimedia file, back to multimedia storage path // </SUMMARY> /// <PARAM name = "ACCESS_TOKEN"> </PARAM> /// <PARAM name = "MEDIA_ID"> </PARAM >/// <RETURNS> </RETURNS> public string GetMultimedia (string ACCESS_TOKEN, string MEDIA_ID) {string file = string. empty; string content = string. empty; string strpath = string. empty; string savepath = string. empty; string stUrl =" http://file.api.weixin.qq.com/cgi-bin/media/get?access_token= "+ ACCESS_TOKEN +" & media_id = "+ MEDIA_ID; HttpWebRequest req = (HttpWebRequest) HttpWebRequest. create (stUrl); req. method = "GET"; using (WebResponse wr = req. getResponse () {HttpWebResponse myResponse = (HttpWebResponse) req. getResponse (); strpath = myResponse. responseUri. toString (); WriteLog ("receiving type: //" + myResponse. contentType); WebClient mywebclient = new WebClient (); savepath = Server. mapPath ("image") + "\" + DateTime. now. toString ("yyyyMMddHHmmssfff") + (new Random ()). next (). toString (). substring (0, 4) + ". jpg "; WriteLog (" Path: // "+ savepath); try {mywebclient. downloadFile (strpath, savepath); file = savepath;} catch (Exception ex) {savepath = ex. toString () ;}} return file ;}

The two parameters above are well understood. The first is ACCESS_TOKEN, which has been mentioned before. The second is the resource id on the server, that is, mediaID. If we want to download resources on the server, we always need to know the id. But how does MEDIA_ID generate it? First, I need to modify the previous message entity class and add the MediaId attribute.

class wxmessage   {     public string FromUserName { get; set; }     public string ToUserName { get; set; }      public string MsgType { get; set; }      public string EventName { get; set; }      public string Content { get; set; }     public string Recognition { get; set; }     public string MediaId { get; set; }     public string EventKey { get; set; }   } 

Modify GetWxMessage () and assign a value to MediaId.

private wxmessage GetWxMessage()    {      wxmessage wx = new wxmessage();      StreamReader str = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8);      XmlDocument xml = new XmlDocument();      xml.Load(str);      wx.ToUserName = xml.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText;      wx.FromUserName = xml.SelectSingleNode("xml").SelectSingleNode("FromUserName").InnerText;      wx.MsgType = xml.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText;      if (wx.MsgType.Trim() == "text")      {        wx.Content = xml.SelectSingleNode("xml").SelectSingleNode("Content").InnerText;      }      if (wx.MsgType.Trim() == "event")      {        wx.EventName = xml.SelectSingleNode("xml").SelectSingleNode("Event").InnerText;        wx.EventKey = xml.SelectSingleNode("xml").SelectSingleNode("EventKey").InnerText;      }      if (wx.MsgType.Trim() == "voice")      {        wx.Recognition = xml.SelectSingleNode("xml").SelectSingleNode("Recognition").InnerText;      }     if (wx.MsgType.Trim() == "image")     {       wx.MediaId = xml.SelectSingleNode("xml").SelectSingleNode("MediaId").InnerText;     }            return wx;    } 

If we are modifying the message acceptance code, we can do it. The customer sends a photo to the platform, the program detects the image, and then according to MediaId, call the GetMultimedia method to download the image to your server. What do you want to do next.
The example just now seems to be a user who sends an image and then sends it to our server through the platform. In another case, the user sends a user name, for example, "hemeng ", then, I need to call the image of the hemeng profile on an existing server to report it to the user. What should I do? How can we send our images to the platform and then to users? The upload method is used:

/// <SUMMARY> /// upload a multimedia file, returns MediaId /// </SUMMARY> /// <PARAM name = "ACCESS_TOKEN"> </PARAM> /// <PARAM name = "Type"> </PARAM>/ // <RETURNS> </RETURNS> public string UploadMultimedia (string ACCESS_TOKEN, string Type) {string result = ""; string wxurl =" http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token= "+ ACCESS_TOKEN +" & type = "+ Type; string filepath = Server. mapPath ("image") + "\ hemeng80.jpg"; (address of the local server) WriteLog ("Upload path:" + filepath); WebClient myWebClient = new WebClient (); myWebClient. credentials = CredentialCache. defaultCredentials; try {byte [] responseArray = myWebClient. uploadFile (wxurl, "POST", filepath); result = System. text. encoding. default. getString (responseArray, 0, responseArray. length); WriteLog ("Upload result:" + result); UploadMM _ mode = JsonHelper. parseFromJson <UPLOADMM> (result); result = _ mode. media_id;} catch (Exception ex) {result = "Error:" + ex. message;} WriteLog ("Upload MediaId:" + result); return result ;}

If the second parameter is an image, you can refer to the document. The Return Value of the function is a MediaId, so that you can use the function of sending the image to send it to the customer. The function of sending the image is as follows:

protected string sendPicTextMessage(Msg _mode, string MediaId)   {     string res = string.Format(@"<xml>                      <ToUserName><![CDATA[{0}]]></ToUserName>                      <FromUserName><![CDATA[{1}]]></FromUserName>                      <CreateTime>{2}</CreateTime>                      <MsgType><![CDATA[image]]></MsgType>                      <Image>                      <MediaId><![CDATA[{3}]]></MediaId>                      </Image>                  </xml> ",       _mode.FromUserName, _mode.ToUserName, DateTime.Now, MediaId);      return res;   } 

Other videos and speech operations are similar, so we will not introduce redundancy. With this knowledge, can we make a lot of applications? Of course we are sure, but our code is not optimized enough, and the structure is unreasonable. Don't worry, we will introduce it gradually, because we haven't fully understood the powerful functions.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.