asp.net 檔案下載與壓縮

iDotNetSpace發表於2010-12-14

1.新增ICSharpCode.SharpZipLib.dll(該元件是壓縮元件)

2.新增一個壓縮輔助類,可以壓縮多個檔案

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;

 

namespace CSharpZipLibHelper
{
    public class SharpZipLibHelper
    {
        //

 
        /// 壓縮指定檔案生成ZIP檔案 
        ///
 
        /// 頂層資料夾名稱 \Storage Card\PDADataExchange\send\xml\ 
        /// 待壓縮檔案列表  file名 ddd.txt 
        /// ZIP檔案  \Storage Card\PDADataExchange\send\zip\version.zip 
        /// 壓縮比  7 
        /// 密碼 "" 
        /// 壓縮檔案註釋文字  "" 
        public static void ZipFile(string topDirName, string[] fileNamesToZip, string ZipedFileName, int CompressionLevel, string password, string comment)
        {
            using (ZipOutputStream s = new ZipOutputStream(System.IO.File.Open(ZipedFileName, FileMode.Create)))
            {
                if (password != null && password.Length > 0)
                    s.Password = password;

                if (comment != null && comment.Length > 0)
                    s.SetComment(comment);

                s.SetLevel(CompressionLevel); // 0 - means store only to 9 - means best compression 
                foreach (string file in fileNamesToZip)
                {
                    using (FileStream fs = File.OpenRead(Path.Combine(topDirName, file)))   //開啟待壓縮檔案 
                    {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);      //讀取檔案流 
                        ZipEntry entry = new ZipEntry(file);    //新建例項 
                        entry.DateTime = DateTime.Now;
                        entry.Size = fs.Length;
                        fs.Close();
                        s.PutNextEntry(entry);
                        s.Write(buffer, 0, buffer.Length);
                    }
                }
                s.Finish();
                s.Close();
            }
        }

        ///

 
        /// 解壓縮ZIP檔案到指定資料夾 
        ///
 
        /// ZIP檔案 
        /// 解壓資料夾 
        /// 壓縮檔案密碼 
        public static void UnZipFile(string zipfileName, string UnZipDir, string password)
        {
            //zipfileName=@"\Storage Card\PDADataExchange\receive\zip\test.zip";
            //UnZipDir= @"\Storage Card\PDADataExchange\receive\xml\";
            //password="";

            ZipInputStream s = new ZipInputStream(File.OpenRead(zipfileName));
            if (password != null && password.Length > 0)
                s.Password = password;
            try
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(UnZipDir);
                    string pathname = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);

                    //生成解壓目錄  
                    pathname = pathname.Replace(":", "$");//處理壓縮時帶有碟符的問題 
                    directoryName = directoryName + "\\" + pathname;
                    Directory.CreateDirectory(directoryName);

                    if (fileName != String.Empty)
                    {
                        //解壓檔案到指定的目錄 
                        FileStream streamWriter = File.Create(directoryName + "\\" + fileName);
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }

                            else
                            {
                                break;
                            }

                        }
                        streamWriter.Close();
                    }
                }
                s.Close();
            }
            catch (Exception eu)
            {
                throw eu;
            }

            finally
            {
                s.Close();
            }
        }
    }
}

頁面前臺程式碼

    CodeFile="Default.aspx.cs" Inherits="_Default" %>

 


   
        var sFeatures = "dialogHeight:50px;dialogWidth:1200px;center:yes;scroll:yes;status:no;";
        function modopen() {
            window.showModalDialog("/Page/hp.aspx", this, sFeatures);
        }
   


   
   


       
       

       
       

       
       
       
       
   

我這裡用了模板頁,需要的人就拿那個幾個button控制元件與文字就可以

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;
using CSharpZipLibHelper;

 

public partial class _Default : System.Web.UI.Page
{

    string path;
    int identity;
    string rootPath;

    protected void Page_Load(object sender, EventArgs e)
    {
        path = Server.MapPath("/File/File.txt");
        rootPath = Server.MapPath("/File/DownLoad/");
        identity = 45000;
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        //  Label1.Text = (Int32.Parse(Label1.Text) + 1).ToString();
        //Label2.Text = (Int32.Parse(Label2.Text) + 1).ToString();


        Thread t = new Thread(() => { WriteFile(); });
        t.Start();
        // Response.Write("

    }

    protected void WriteFile()
    {
        int count = int.Parse(TextBox1.Text.Trim());
        FileStream fs = File.Open(path, FileMode.Create, FileAccess.ReadWrite);
        string s = DateTime.Now.ToString("yyyyMMddHHmmss");
        using (StreamWriter sw = new StreamWriter(fs))
        {
            for (int i = 1; i <= count; i++)
            {
                sw.WriteLine(i + ":    " + s + i.ToString());
            }
        }
    }

    protected void Button3_Click(object sender, EventArgs e)
    {

        if (!Directory.Exists(rootPath))
        {
            Directory.CreateDirectory(rootPath);
        }
        Thread t = new Thread(() =>
        {
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);

            using (fs)
            {
                StreamReader sr = new StreamReader(fs);
                StringBuilder sb = new StringBuilder();
                List FileNames = new List();
                string rootPathDate = rootPath + DateTime.Now.Year.ToString() + "\\";
                if (!Directory.Exists(rootPathDate))
                {
                    Directory.CreateDirectory(rootPathDate);
                }

                string line = sr.ReadLine();
                int i = 1;
                int j = 0;
                while (line != null && j < i * identity)
                {
                    sb.AppendLine(line);

                    line = sr.ReadLine();
                    j++;

                    if (line == null || (line != null && j == i * identity))
                    {
                        FileNames.Add(WriteFile(rootPathDate, sb.ToString()));
                        sb = sb.Clear();
                        i++;
                    }
                }

                if (FileNames.Count > 0)
                {
                    Compress(rootPathDate, FileNames);
                }
            }
        });
        t.Start();
    }

    ///


    /// 寫檔案
    ///

    protected string WriteFile(string RootPath, string FileTxt)
    {
        string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt";
        string FilePath = Path.Combine(RootPath, FileName);
        using (FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            StreamWriter sw = new StreamWriter(fs);
            using (sw)
            {
                sw.Write(FileTxt);
            }
        }
        return FileName;
    }

    public string Compress(string RootPath, List filename)
    {
        //   壓縮   
        string Name = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".zip";
        string FileName = Path.Combine(RootPath, Name);
        string topPath = Path.GetPathRoot(RootPath);

        SharpZipLibHelper.ZipFile(RootPath, filename.ToArray(), FileName, 7, "", "");

        return FileName;
    }

    protected void Button4_Click(object sender, EventArgs e)
    {
        Page.Response.Clear();
        bool success = ResponseFile(Page.Request, Page.Response, "20101212225148156.zip", @"/File/DownLoad/2010/", 1024000);
        if (!success)
            Response.Write("下載檔案出錯!");
        Page.Response.End();
    }

    public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
    {
        try
        {
            FileStream myFile = new FileStream(HttpContext.Current.Server.MapPath(Path.Combine(_fullPath, _fileName)), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                _Response.AddHeader("Accept-Ranges", "bytes");
                _Response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;

                double pack = 10240; //10K bytes
                //int sleep = 200;   //每秒5次   即5*10K bytes每秒
                int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
                if (_Request.Headers["Range"] != null)
                {
                    _Response.StatusCode = 206;
                    string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    //Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
                }
                _Response.AddHeader("Connection", "Keep-Alive");
                _Response.ContentType = "application/octet-stream";
                _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;

                for (int i = 0; i < maxCount; i++)
                {
                    if (_Response.IsClientConnected)
                    {
                        _Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                br.Close();

                myFile.Close();
            }
        }
        catch
        {
            return false;
        }
        return true;
    }
}

後臺程式碼。

直接copy去用就可以

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-681745/,如需轉載,請註明出處,否則將追究法律責任。

相關文章