C#通过文件流下载文件

1、该方法传入的参数为需要下载的文件(需要包含绝对路径)

        /// <summary>
        /// 通过文件流下载文件
        /// </summary>
        /// <param name="url">文件名称(包含目录和后缀名)</param>
        private void DownLoadPic(string url)
        {
            string sFileName = url ;
            FileStream fileStream = new FileStream(sFileName, FileMode.Open);
            long fileSize = fileStream.Length;
            byte[] fileBuffer = new byte[fileSize];
            fileStream.Read(fileBuffer, 0, (int)fileSize);
            //如果不写fileStream.Close()语句,用户在下载过程中选择取消,将不能再次下载
            fileStream.Close();

            Context.Response.ContentType = "application/octet-stream";
            Context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(这里是你想要下载文件的文件名), Encoding.UTF8));
            Context.Response.AddHeader("Content-Length", fileSize.ToString());

            Context.Response.BinaryWrite(fileBuffer);
            Context.Response.End();
            Context.Response.Close();
        }

2、下载指定路径的文件


        /// <summary>
        /// 文件流方式下载附件
        /// </summary>
        /// <param name="path">包含文件名的相对路径</param>
        /// <param name="name">下载后的新文件名</param>
        public static void DownloadFile(string path, string name)
        {
            if (!string.IsNullOrEmpty(path))
            {
                string filePath = HttpContext.Current.Server.MapPath(path);
                FileInfo fileInfo = new FileInfo(filePath);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Encoding.GetEncoding(65001).GetBytes(name)));
                HttpContext.Current.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.WriteFile(fileInfo.FullName);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
        }



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值