Thursday, November 26, 2009

Download multiple files as a zip folder in asp.net

The following post is for downloading multiple files as a zip folder in asp.net,
In .aspx :

<div>
    <asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="false">
  
    <Columns>
  
    <asp:TemplateField>
    <ItemTemplate>
    <asp:CheckBox ID="chkSelect" runat="server" />
    </ItemTemplate>
    </asp:TemplateField>
              
    <asp:TemplateField HeaderText="File Name">
      
  
    <ItemTemplate>
    <asp:Label ID="lblFileName" runat="server" Text='<%# Eval("FileName") %>' />
    <asp:Label ID="lblFilePath" Visible="false" runat="server" Text='<%# Eval("FilePath") %>' />
    </ItemTemplate>
    </asp:TemplateField>
  
    </Columns>
  
    </asp:GridView>
  
    <br />
    <asp:Button ID="btn_DownloadAll" runat="server" Text="Download" OnClick="Btn_Download_All_Click" />
  
    <asp:Label ID="lblMessage" runat="server" Font-Size="16" BackColor="Red" />

    </div>

In .aspx.cs:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;


public partial class MultipleFiledownload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindData();
        }
    }
    private void BindData()
    {
        var files = Directory.GetFiles(Server.MapPath("~/Files"));


        gvFiles.DataSource = from f in files
                             select new
                                        {
                                            FileName = Path.GetFileName(f),
                                            FilePath = f
                                        };
        gvFiles.DataBind();
    }


    protected void Btn_Download_All_Click(object sender, EventArgs e)
    {
        // download all the files 
        ZipAllFiles();


    }


    private void ZipAllFiles()
    {
        byte[] buffer = new byte[4096];


        // the path on the server where the temp file will be created!
        var tempFileName = Server.MapPath(@"TempFiles/" + Guid.NewGuid().ToString() + ".zip");


        var zipOutputStream = new ZipOutputStream(File.Create(tempFileName));
        var filePath = String.Empty;
        var fileName = String.Empty;
        var readBytes = 0;


        foreach (GridViewRow row in gvFiles.Rows)
        {
            var isChecked = (row.FindControl("chkSelect") as CheckBox).Checked;
            if (!isChecked) continue;


            filePath = (row.FindControl("lblFilePath") as Label).Text;
            fileName = (row.FindControl("lblFileName") as Label).Text;


            var zipEntry = new ZipEntry(fileName);


            zipOutputStream.PutNextEntry(zipEntry);


            using (var fs = File.OpenRead(filePath))
            {
                do
                {
                    readBytes = fs.Read(buffer, 0, buffer.Length);
                    zipOutputStream.Write(buffer, 0, readBytes);


                } while (readBytes > 0);
            }
        }


        if (zipOutputStream.Length == 0)
        {
            lblMessage.Text = "Please select at least one file!";
            return;
        }




        zipOutputStream.Finish();
        zipOutputStream.Close();


        Response.ContentType = "application/x-zip-compressed";
        Response.AppendHeader("Content-Disposition", "attachment; filename=YourFile.zip");
        Response.WriteFile(tempFileName);


        Response.Flush();
        Response.Close();


        // delete the temp file 
        if (File.Exists(tempFileName))
            File.Delete(tempFileName);
    }
}





No comments:

Post a Comment