• 微信下载远程图片的公用方法


    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Text.RegularExpressions;
    
    namespace Wisdom.JPClient.WeiXin.Utility
    {
        public class CommonUtility
        {
            public static bool IsGUID(string str)
            {
                Match m = Regex.Match(str, @"^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$", RegexOptions.IgnoreCase);
                if (m.Success)
                {
                    //可以转换 
                    //Guid guid = new Guid(str);
                    return true;
                }
                else
                {
                    //不可转换 
                    return false;
                }
            }
    
            /// <summary>
            /// 获取远程图片
            /// </summary>
            /// <param name="imgUrl">远程图片地址</param>
            /// <param name="path">文件夹名</param>
            /// <returns></returns>
            public static int SaveImageFromWeb(string imgUrl, string Pic_Path_IDCard, ref string NewPicName)
            {
                NewPicName = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(10, 100);
                var aaa = Environment.CurrentDirectory;
                string imgName = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("/") + 1);
                if (Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("~/UploadFiles/" + Pic_Path_IDCard + "/")) == false)//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~/UploadFiles/" + Pic_Path_IDCard + "/"));
                }
                string path = System.Web.HttpContext.Current.Server.MapPath(String.Format("/UploadFiles/" + Pic_Path_IDCard + "/{0}", NewPicName));
                //path = path + "//" + imgName;
                string defaultType = ".jpg";
                string[] imgTypes = new string[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
                string imgType = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("."));
                foreach (string it in imgTypes)
                {
                    if (imgType.ToLower().Equals(it))
                        break;
                    if (it.Equals(".bmp"))
                        imgType = defaultType;
                }
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgUrl);
                    request.UserAgent = "Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; Natas.Robot)";
                    request.Timeout = 10000;
                    WebResponse response = request.GetResponse();
                    Stream stream = response.GetResponseStream();
                    if (response.ContentType.ToLower().StartsWith("image/"))
                    {
                        byte[] arrayByte = new byte[1024];
                        int imgLong = (int)response.ContentLength;
                        int l = 0;
                        // CreateDirectory(path);
                        FileStream fso = new FileStream(path, FileMode.Create);
                        while (l < imgLong)
                        {
                            int i = stream.Read(arrayByte, 0, 1024);
                            fso.Write(arrayByte, 0, i);
                            l += i;
                        }
                        fso.Close();
                        stream.Close();
                        response.Close();
                        return 1;
                    }
                    else
                    {
                        return 0;
                    }
                }
                catch (WebException)
                {
                    return 0;
                }
                catch (UriFormatException)
                {
                    return 0;
                }
            }
    
            /// <summary>
            /// 返回中文周几,
            /// </summary>
            /// <param name="y"></param>
            /// <param name="m"></param>
            /// <param name="d"></param>
            /// <returns></returns>
            public static string CaculateChineseWeekDay(int y, int m, int d)
            {
                if (m == 1) m = 13;
                if (m == 2) m = 14;
                int week = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7 + 1;
                string weekstr = "";
                switch (week)
                {
                    case 1: weekstr = "周一"; break;
                    case 2: weekstr = "周二"; break;
                    case 3: weekstr = "周三"; break;
                    case 4: weekstr = "周四"; break;
                    case 5: weekstr = "周五"; break;
                    case 6: weekstr = "周六"; break;
                    case 7: weekstr = "周日"; break;
                }
    
                return weekstr;
            }
    
    
    
    
            /// <summary>
            /// 下载保存多媒体文件,返回多媒体保存路径
            /// </summary>
            /// <param name="ACCESS_TOKEN"></param>
            /// <param name="MEDIA_ID"></param>
            /// <returns></returns>
            public static string GetMultimedia(string ACCESS_TOKEN, string MEDIA_ID, string fileName, ref string NewPicName)
            {
                NewPicName = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(10, 100) + ".jpg";
                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;
    
                if (Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("~/UploadFiles/" + fileName + "/")) == false)//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~/UploadFiles/" + fileName + "/"));
                }
    
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(stUrl);
    
                req.Method = "GET";
                using (WebResponse wr = req.GetResponse())
                {
                    HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();
    
                    strpath = myResponse.ResponseUri.ToString();
                    WebClient mywebclient = new WebClient();
                    savepath = System.Web.HttpContext.Current.Server.MapPath(String.Format("/UploadFiles/" + fileName + "/{0}", NewPicName));
                    try
                    {
                        mywebclient.DownloadFile(strpath, savepath);
                        file = savepath;
                    }
                    catch (Exception ex)
                    {
                        savepath = ex.ToString();
                    }
    
                }
                return file;
            }
    
    
    
            ///   <summary> 
            ///   将指定字符串按指定长度进行截取并加上指定的后缀
            ///   </summary> 
            ///   <param   name= "oldStr "> 需要截断的字符串 </param> 
            ///   <param   name= "maxLength "> 字符串的最大长度 </param> 
            ///   <param   name= "endWith "> 超过长度的后缀 </param> 
            ///   <returns> 如果超过长度,返回截断后的新字符串加上后缀,否则,返回原字符串 </returns> 
            public static string StringTruncat(string oldStr, int maxLength, string endWith)
            {
                //判断原字符串是否为空
                if (string.IsNullOrEmpty(oldStr))
                    return oldStr + endWith;
    
    
                //返回字符串的长度必须大于1
                if (maxLength < 1)
                    throw new Exception("返回的字符串长度必须大于[0] ");
    
    
                //判断原字符串是否大于最大长度
                if (oldStr.Length > maxLength)
                {
                    //截取原字符串
                    string strTmp = oldStr.Substring(0, maxLength);
    
    
                    //判断后缀是否为空
                    if (string.IsNullOrEmpty(endWith))
                        return strTmp;
                    else
                        return strTmp + endWith;
                }
                return oldStr;
            }
    
            /// <summary>
            /// post方法
            /// </summary>
            /// <param name="postUrl">url地址</param>
            /// <param name="paramData">提交的ParamData对象</param>
            /// <returns></returns>
            public static string PostWebRequest<T>(string postUrl, T paramData)
            {
                string ret = string.Empty;
                try
                {
                    string str_Tem = JsonConvert.SerializeObject(paramData);//将对象转成json串
                    byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(str_Tem);
                    HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                    webReq.Method = "POST";
                    webReq.ContentType = " application/json; charset=utf-8";
                    webReq.ContentLength = byteArray.Length;
                    Stream newStream = webReq.GetRequestStream();
                    newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                    newStream.Close();
                    HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                    StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    ret = sr.ReadToEnd();
                    sr.Close();
                    response.Close();
                    newStream.Close();
                }
                catch (Exception ex)
                {
    
                }
                return ret;
            }
    
            /// <summary>
            /// C#反序列化JSON
            /// </summary>
            /// <typeparam name="T">返回类型</typeparam>
            /// <param name="jsonString">JSON字符串</param>
            /// <returns></returns>
            public static T JsonDeserialize<T>(string strJson)
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson));
                T objT = (T)ser.ReadObject(ms);
                ms.Close();
                return objT;
            }
        }
    }
  • 相关阅读:
    利用if else判断几点是什么时间段
    【UML】活动图介绍
    【UML】类图介绍
    jQuery Ajax跨域问题简易解决方案
    ASP.NET MVC @Html.Label的问题
    Mysql Show ProcessList命令
    【ASP.NET MVC 学习笔记】- 20 ASP.NET Web API
    【ASP.NET MVC 学习笔记】- 19 REST和RESTful Web API
    【ASP.NET MVC 学习笔记】- 18 Bundle(捆绑)
    【ASP.NET MVC 学习笔记】- 17 Model验证
  • 原文地址:https://www.cnblogs.com/muxueyuan/p/5593207.html
Copyright © 2020-2023  润新知