.Net MVC读取网络路径URI 后台处理

 判断是否是网络路径

#region 识别urlStr是否是网络路径
        /// <summary>
        /// 识别urlStr是否是网络路径
        /// </summary>
        /// <param name="urlStr"></param>
        /// <returns></returns>
        public static bool UrlDiscern(string urlStr)
        {
            if (Regex.IsMatch(urlStr, @"((http|ftp|https)://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

 判断网络路径是否存在


        /// <summary>
        /// 检查uri链接是否有效
        /// </summary>
        /// <param name="strUri"></param>
        /// <returns></returns>
        public static bool CheckUri(string strUri)
        {
            try
            {
                System.Net.HttpWebRequest.Create(strUri).GetResponse();
                return true;
            }
            catch
            {
                return false;
            }
        }

 将获取网络路径图片转化成流数据

     /// <summary>
        /// 图片以流数据返回
        /// </summary>
        /// <param name="path">网络路径</param>
        /// <returns></returns>
        public ActionResult show(string path)
        {         
            bool flag = CheckUri(path);
            if (!flag)
            {
                string file = Server.MapPath("/Content/20180726_0001.jpg");//默认图片
                byte[] imgByte = System.IO.File.ReadAllBytes(file);
                return File(imgByte, "image/jpg");
            }
            WebRequest request = WebRequest.Create(path);
            WebResponse response = request.GetResponse();
            Stream s = response.GetResponseStream();
            byte[] data = new byte[1024];
            int length = 0;
            MemoryStream ms = new MemoryStream();
            while ((length = s.Read(data, 0, data.Length)) > 0)
            {
                ms.Write(data, 0, length);
            }
            ms.Seek(0, SeekOrigin.Begin);
     
            return File(ms, "image/jpg");             
        }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值