zoukankan      html  css  js  c++  java
  • C#/.Net文件打包下载

     Dictionary<string, Stream> streams = new Dictionary<string, Stream> ();
     Stream streamWriter = null;
    
    //将所有文件流在循环中加进,根据自己情况来写

        streamWriter = File.Open(filePath, FileMode.Open);
        streams.Add(strName, streamWriter);

     //下面可以直接复制粘贴
      MemoryStream ms = new MemoryStream();
      ms = PackageManyZip(streams);
      byte[] bytes = new byte[(int)ms.Length];
      ms.Read(bytes, 0, bytes.Length);
      ms.Close();
      Response.ContentType = "application/octet-stream";
      //通知浏览器下载文件而不是打开
      Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode("打包文档.zip", System.Text.Encoding.UTF8));
      Response.BinaryWrite(bytes);
      Response.Flush();
     /// <summary>
         /// 将多个流进行zip压缩,返回压缩后的流
         /// </summary>
         /// <param name="streams">key:文件名;value:文件名对应的要压缩的流</param>
         /// <returns>压缩后的流</returns>
        static MemoryStream PackageManyZip(Dictionary<string, Stream> streams)
        {
            byte[] buffer = new byte[6500];
            MemoryStream returnStream = new MemoryStream();
            var zipMs = new MemoryStream();
            using (ZipOutputStream zipStream = new ZipOutputStream(zipMs))
            {
                zipStream.SetLevel(9);
                foreach (var kv in streams)
                {
                    string fileName = kv.Key;
                    using (var streamInput = kv.Value)
                    {
                        zipStream.PutNextEntry(new ZipEntry(fileName));
                        while (true)
                        {
                            var readCount = streamInput.Read(buffer, 0, buffer.Length);
                            if (readCount > 0)
                            {
                                zipStream.Write(buffer, 0, readCount);
                            }
                            else
                            {
                                break;
                            }
                        }
                        zipStream.Flush();
                    }
                }
                zipStream.Finish();
                zipMs.Position = 0;
                zipMs.CopyTo(returnStream, 5600);
            }
            returnStream.Position = 0;
            return returnStream;
        }

     

  • 相关阅读:
    uva514Rails(栈)
    hdu1160FatMouse's Speed
    如何截取整个屏幕
    equals 与==
    (转载)equals与==
    (转载)关于ArrayList的5道面试题
    java的一些程序
    (转载)OSI七层参考模型和TCP/IP四层参考模型
    (转载)算法面试题
    (转载)火车运煤
  • 原文地址:https://www.cnblogs.com/wangjiaxiaoxi/p/7551361.html
Copyright © 2011-2022 走看看