.net实现下载文件

1.下载单个文件 

   /// <summary>
        /// 下载excel
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="fileName"></param>
        private void ResponseBinaryWrite(MemoryStream stream, string fileName)
        {
 
            Response.Charset = "GB2312";
            Context.Response.ContentType = "application/octet-stream";
            Context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("参与人员清单.xls"));
            Context.Response.AddHeader("Content-Length", stream.Length.ToString());
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置输出流为简体中文
            Context.Response.BinaryWrite(stream.ToArray());
            Context.Response.Flush();
            Context.Response.End();
            Context.Response.Close();

        }

2.批量打包成zip下载,需要ICSharpCode.SharpZipLib.dll

        /// <summary>  
        /// 多文件打包下载
        /// </summary>  
        public void DwonloadZip(string[] filePathList, string zipName)
        {

            MemoryStream ms = new MemoryStream();
            byte[] buffer = null;
            var context = HttpContext.Current;
            using (ICSharpCode.SharpZipLib.Zip.ZipFile file = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(ms))
            {
                file.BeginUpdate();
                file.NameTransform = new MyNameTransfom();//通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。
                foreach (var it in filePathList)
                {
                    //file.Add(context.Server.MapPath(it));
                    if (!string.IsNullOrEmpty(it))
                    {
                        file.Add(it);
                    }
                }
                file.CommitUpdate();

                buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
            }
            Response.Charset = "GB2312";
            Context.Response.ContentType = "application/octet-stream";
            context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            context.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(zipName));
            context.Response.BinaryWrite(buffer);
         
            context.Response.Flush();
            context.Response.End();
        }


        public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform
        {

            #region INameTransform 成员

            public string TransformDirectory(string name)
            {
                return null;
            }

            public string TransformFile(string name)
            {
                return Path.GetFileName(name);
            }

            #endregion
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章