• C# 后台获取请求来源、文件下载


     HTTP请求下载文件

    /// <summary>
    /// Http方式下载文件
    /// </summary>
    /// <param name="url">url地址</param>
    /// <param name="path">路径</param>
    /// <param name="fileName">文件名</param>
    /// <returns></returns>
    public static bool HttpDownLoadold(string url, string path, string fileName)
    {
         bool flag = false;
         long startPosition = 0; // 上次下载的文件起始位置
         FileStream writeStream; // 写入本地文件流对象
         // 判断文件夹是否存在
         if (Directory.Exists(path) == false)
         {
              Directory.CreateDirectory(path);
         }
         //判断文件是否存在
         if (File.Exists(fileName))
         {
             writeStream = File.OpenWrite(fileName);             // 存在则打开要下载的文件
             startPosition = writeStream.Length;                  // 获取已经下载的长度
             writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位
         }
         else
         {
             writeStream = new FileStream(path + fileName, FileMode.Create);// 文件不保存创建一个文件
             startPosition = 0;
         }
         try
         {
             HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
             if (startPosition > 0)
             {
                   myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
             }
             Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流
             byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
             int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次
             while (contentSize > 0)// 如果读取长度大于零则继续读
             {
                   writeStream.Write(btArray, 0, contentSize);// 写入本地文件
                   contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
             }
             //关闭流
             writeStream.Close();
             readStream.Close();
             flag = true;        //返回true下载成功
             }
             catch (Exception)
             {
                  writeStream.Close();
                  flag = false;       //返回false下载失败
             }
             return flag;
     }

    文件流下载文件

     void BigFileDownload()
            {
                try
                {
                    string FileName = "测试.docx";
                    string filePath = Page.Server.MapPath("~/Content/测试.docx");
                    //以字符流的形式下载文件
                    FileStream fs = new FileStream(filePath, FileMode.Open);
                    byte[] bytes = new byte[(int)fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    fs.Close();
                    Response.ContentType = "application/octet-stream;charset=gb2321";
    
                    //通知浏览器下载文件而不是打开;对中文名称进行编码
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
                    Response.BinaryWrite(bytes);
                }
                catch (Exception ex)
                {
    
                }
                finally
                {
                    Response.Flush();
                    Response.End();
                }
            }

    asp.net mvc 获取请求源

     /// <summary>
            /// 下载APP
            /// </summary>
            /// <returns></returns>
            [AllowAnonymous]
            [Route("download/app")]
            public ActionResult DownloadApp() {
    
                string android = "android";
                //获取客服端请求源
                string agent = Request.UserAgent;
                string[] keywords = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };
    
                // CloudWave.Framework.Core.Logging.Logging4net.WriteInfo(agent);
                //排除 Windows 桌面系统           
                //if (!agent.Contains("Windows NT") || (agent.Contains("Windows NT") && agent.Contains("compatible; MSIE 9.0;")))
                var downloadurl = "";
                //判断是微信, 直接响应应用宝地址
                if (agent.ToLower().Contains("micromessenger")) {
                    //获取配置信息
                    var wxUrl = ConfigurationManager.AppSettings["YingYongBao"];
                    if (!string.IsNullOrEmpty(wxUrl)) {
                        return Redirect(wxUrl);
                    }
                    return RedirectToAction("index");
                }
                if (agent.ToLower().Contains(android)) {
                    downloadurl = ConfigurationManager.AppSettings["AndroidUrl"];
                    if (string.IsNullOrEmpty(downloadurl)) {
                        return RedirectToAction("index");
                    }
                } else {
                    downloadurl = ConfigurationManager.AppSettings["IOSUrl"];
                    if (string.IsNullOrEmpty(downloadurl)) {
                        return RedirectToAction("index");
                    }
                    if (agent.ToLower().Contains("weibo")) {
                        downloadurl = "itms-apps" + downloadurl.Substring(downloadurl.IndexOf(":")); //itms-apps://
                    }
                }
                return Redirect(downloadurl);
            }
  • 相关阅读:
    GO学习-(31) Go语言操作Elasticsearch
    GO学习-(30) Go语言操作kafka
    GO学习-(29) Go语言操作etcd
    Maven+Spring打Jar包
    话说Session
    Apache Server与多个独立Tomcat集成
    一套Tomcat处理多个域名请求
    Tomcat多实例
    Linux下安装MySQL
    Java Enum
  • 原文地址:https://www.cnblogs.com/miskis/p/7097954.html
Copyright © 2020-2023  润新知