.net下载文件的方法

最近做项目遇到文件下载的问题,原本采用的是直接用一个href链接到需要下载的文件来处理这个问题,后来发现,如果文件是一个图片,浏览器会自动打开图片而不是下载,需要用户右击另存为才可以下载,很不友好,后来上网找了一个a标签的download属性,经测试,谷歌浏览器支持下载,但是IE并不支持这个属性,懒得去做那些兼容的操作了,在后台写了一个下载的方法,直接前台调用就OK

  • asp.net的下载方法
/// <summary>
       ///字符流下载方法
       /// </summary>
       /// <param name="fileName">下载文件生成的名称</param>
       /// <param name="fPath">下载文件路径</param>
       /// <returns></returns>
        public void DownloadFile(string fileName, string fPath)
        {
            string filePath = Server.MapPath(fPath);//路径
            //以字符流的形式下载文件
            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";
            //通知浏览器下载文件而不是打开
            Response.AddHeader("Content-Disposition", "attachment;   filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
  •  asp.net MVC 的下载方法
/// <summary>
        /// 下载文件的方法
        /// </summary>
        /// <param name="path">文件绝对路径</param>
        /// <param name="fileName">客户端接收的文件名</param>
        /// <returns></returns>
        public static HttpResponseMessage Download(string path, string fileName)
        {
            var stream = File.OpenRead(path);
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
            try
            {
                httpResponseMessage.Content = new StreamContent(stream);
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                if (!string.IsNullOrEmpty(fileName))
                {
                    httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8),
                    };
                }
                return httpResponseMessage;
            }
            catch
            {
                stream.Dispose();
                httpResponseMessage.Dispose();
                throw;
            }
        }
  • .net Core 的下载方法
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="path">文件绝对路径</param>
        /// <returns></returns>
        public ActionResult<dynamic> DownloadFiles(string path)
        {
            return File(new FileInfo(path).OpenRead(), "application/vnd.android.package-archive", "自定义的文件名");
        }
原文地址:https://www.cnblogs.com/yuchenghao/p/7943329.html