Exemple #1
0
        public void Test()
        {
            var html = @"<img src=""http://karldu.cn/api/SysFile/Download?objectId=09f1f7cb-5b69-44e4-9a30-2eac785520a0"" alt=""image.png"">";
            var list = HtmlUtil.GetHtmlImageUrlList(html);

            Assert.IsTrue(list != null && list.Count > 0);
            Assert.IsTrue(list[0] == "http://karldu.cn/api/SysFile/Download?objectId=09f1f7cb-5b69-44e4-9a30-2eac785520a0");
        }
        /// <summary>
        /// 转换Url为微信媒体Url
        /// </summary>
        /// <param name="htmlContent"></param>
        /// <returns></returns>
        public string ConvertLocalUrlToWeChatUrl(string htmlContent)
        {
            var picList = HtmlUtil.GetHtmlImageUrlList(htmlContent).Distinct();

            if (!picList.IsEmpty())
            {
                var dic = new Dictionary <string, string>(); // 替换url
                picList.Each(item =>
                {
                    var start  = item.IndexOf("objectId=") + 9;
                    var fileid = item.Substring(start, item.Length - start);
                    var url    = CreateData(fileid);
                    dic.TryAdd(item, url);
                });
                htmlContent = htmlContent.Replace(dic);
            }
            return(htmlContent);
        }
        /// <summary>
        /// 转换微信素材地址为本地地址
        /// </summary>
        /// <param name="htmlContent"></param>
        /// <returns></returns>
        public string ConvertWeChatUrlToLocalUrl(string htmlContent)
        {
            #region 更换data-src为src
            var imageTags = HtmlUtil.GetHtmlImagelList(htmlContent);
            if (!imageTags.IsEmpty())
            {
                var dic = new Dictionary <string, string>(); // 替换url
                imageTags.Each(item =>
                {
                    dic.TryAdd(item, item.Replace("data-src", "src"));
                });
                htmlContent = htmlContent.Replace(dic);
            }
            #endregion

            #region 更换地址为本地地址
            var picList = HtmlUtil.GetHtmlImageUrlList(htmlContent).Distinct();
            if (!picList.IsEmpty())
            {
                var dic = new Dictionary <string, string>(); // 替换url
                picList.Each(item =>
                {
                    var identity = item.Split("/")[4];
                    var sql      = "SELECT * FROM wechat_news_material WHERE media_url like concat('%', @url, '%')";
                    var data     = Broker.Retrieve <wechat_news_material>(sql, new Dictionary <string, object>()
                    {
                        { "@url", identity }
                    });
                    if (data != null)
                    {
                        dic.TryAdd(item, data.local_url);
                    }
                });
                htmlContent = htmlContent.Replace(dic);
            }
            #endregion

            return(htmlContent);
        }