關於微信小程序獲取小程序碼並接受buffer流保存爲圖片

前言html

  昨天由於小程序功能要獲取小程序程序碼,看了微信文檔爬了好多坑。(留一下記錄以防後面被坑)前端

操做小程序

  由於我獲取到了微信那裏的圖片的圖片流一直不知道怎麼處理,今天總算找到相關文檔,解決了。由於數據流不能直接傳給前端,只好把buffer流轉成圖片保存在服務器上,沒辦法啊~微信小程序

廢話很少說上代碼 數組

 public static string Api_Post(string postUrl, string postData, WebHeaderCollection header = null,bool isPic=false)
     { Stream outstream
= null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); // 準備請求... try { // 設置參數 request = WebRequest.Create(postUrl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; if (header != null) request.Headers = header; request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //發送請求並獲取相應迴應數據 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序纔開始向目標網頁發送Post請求 instream = response.GetResponseStream();
if (isPic) { byte[] tt = StreamToBytes(instream);//將數據流轉爲byte[] System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath("~/WxCode.jpg"), tt); WxQRCodeModel model = new WxQRCodeModel(); model.data = "192.168.1.216:80/WxCode.jpg"; model.errcode = 0; string content = Config.js.Serialize(model); string err = string.Empty; return content; } else { sr = new StreamReader(instream, encoding); //返回結果網頁(html)代碼 string content = sr.ReadToEnd(); string err = string.Empty; return content; } } catch (Exception ex) { if (isPic) { sr = new StreamReader(instream, encoding); //返回結果網頁(html)代碼 string content = sr.ReadToEnd(); string err = string.Empty; return content; } else { string err = ex.Message; return string.Empty; } } }

由於是instream接受到微信接口那裏發送過來的數據流,就在instream那裏處理,把數據流轉換爲byte[]數組,而後依靠File的WriteAllBytes方法把轉換OK的byte[]數組轉換爲圖片存放在服務器上,而後把圖片路徑交給model。服務器

       ///將數據流轉爲byte[]
        public static byte[] StreamToBytes(Stream stream)
        {
            List<byte> bytes = new List<byte>();
            int temp = stream.ReadByte();
            while (temp != -1)
            {
                bytes.Add((byte)temp);
                temp = stream.ReadByte();
            }
            return bytes.ToArray();
        }

結尾微信

最近才接觸到微信小程序開發,emmmm。以爲本身摸魚摸得好厲害,不過終於把坑爬出來,特別開心。哈哈哈~之後要多多寫開發記錄。上班期間碼得很隨意cookie

相關文章
相關標籤/搜索