返回流的形式下载文件

 //下载文件
    private void Down(HttpContext context)
    {
        string filePath = context.Request["url"];
        if (!string.IsNullOrEmpty(filePath))
        {
            string customFileName = DateTime.Now.ToString("yyyyMMddHHmmss");//客户端保存的文件名  
            using (FileStream fileStream = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                byte[] fileData = new byte[fileStream.Length];
                fileStream.Read(fileData, 0, fileData.Length);
                string fileName = Path.GetFileNameWithoutExtension(filePath);
                                                //attachment 作为附件打开 inline 在线打开
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString());
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
                HttpContext.Current.Response.BinaryWrite(fileData);
            }
        }
    }

 

posted @ 2017-08-04 17:32  独孤小天天  阅读(208)  评论(0编辑  收藏  举报