.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
        }

 

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