(How to download multi files  in ASP.Net) – Khi có 1 danh sách các file cần Download, nếu phải kích vào từng File để Download thì mất rất nhiều thời gian cho người dùng. Vậy có cách nào để có thể chọn các file cần và Click một lần là toàn bộ các file này sẽ được Download. Bài viết dưới đây sẽ hướng dẫn các bạn thực hiện điều đó.

Nghe những bài hát đỉnh nhất về Thấy cô giáo - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



B1: Tạo Project trong Microsoft Visual Studio 2010

B2: Download thư viện SharpZipLib.dll và References vào Project

B3: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML
C# Code
<%@ PageTitle="Download Multiple Files in ASP.Net using C# and VB.Net" Language="C#"MasterPageFile="~/Site.master"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="DownloadMultipleFiles._Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <table cellpadding="3"cellspacing="5"border="0"width="100%">
        <tr>
            <td>
                <divclass="panel panel-default">
                    <divclass="panel-heading">
                        <asp:label id="lblHeader" runat="server" Text="Download Multiple Files"></asp:label>
                    </div>
                    <divclass="panel-body">
                        <table cellspacing="2" cellpadding="3" border="0" width="100%">
                            <tr>
                                <td>
                                    <asp:LinkButton id="cmdDownload"runat="server"CssClass="btn btn-small" OnClick="cmdDownload_Click" Causesvalidation="false">
                                        <i class="icon-download"></i>&nbsp;&nbsp;<asp:label id="lblDownload" runat="server" Text="Download All"></asp:label>
                                    </asp:LinkButton>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:GridView ID="grvObject"runat="server"AllowPaging="true"PageSize="8"
                                        CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
                                        BorderWidth="1"AutoGenerateColumns="false"width="100%"onrowdatabound="grvObject_RowDataBound">
                                        <AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
                                        <HeaderStyle CssClass="GridStyle_HeaderStyle"/>
                                        <RowStyle CssClass="GridStyle_RowStyle"/>
                                        <pagerstyle cssclass="GridStyle_pagination"/>
                                        <Columns>
                                            <asp:TemplateField>
                                                <ItemStyleHorizontalAlign="Center"width="1%"/>
                                                <HeaderTemplate>
                                                    <asp:CheckBox ID="chkAll" runat="server"/>
                                                </HeaderTemplate>
                                                <ItemTemplate>
                                                    <asp:CheckBox ID="chkSelect"runat="server"/>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="Name"SortExpression="Name">
                                            <ItemTemplate>
                                                <asp:Label ID="lblFileName"Visible="false"runat="server"></asp:Label>
                                                <asp:Literal runat="server"ID="ltlFileItem"></asp:Literal>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:BoundField DataField="CreationTime"HeaderText="Creation Time" SortExpression="CreationTime" />
                                        <asp:BoundField DataField="LastWriteTime"HeaderText="Date Modified" SortExpression="LastWriteTime" />
                                        <asp:TemplateField HeaderText="Size"SortExpression="Size"ItemStyle-HorizontalAlign="Right">
                                            <ItemStyle HorizontalAlign="Right"></ItemStyle>
                                            <ItemTemplate>
                                                <%# DisplaySize((long?) Eval("Size")) %>
                                            </ItemTemplate>
                                        </asp:TemplateField>                       
                                        </Columns>                               
                                    </asp:GridView>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </td>
        </tr>       
    </table>
</asp:Content>
VB.NET Code
<%@ PageTitle="Download Multiple Files in ASP.Net using C# and VB.Net" Language="vb"MasterPageFile="~/Site.Master"AutoEventWireup="false"CodeBehind="Default.aspx.vb"Inherits="DownloadMultipleFiles._Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <table cellpadding="3"cellspacing="5"border="0"width="100%">
        <tr>
            <td>
                <divclass="panel panel-default">
                    <divclass="panel-heading">
                        <asp:label id="lblHeader" runat="server" Text="Download Multiple Files"></asp:label>
                    </div>
                    <divclass="panel-body">
                        <table cellspacing="2"cellpadding="3"border="0"width="100%">
                            <tr>
                                <td>
                                    <asp:LinkButton id="cmdDownload"runat="server"CssClass="btn btn-small" Causesvalidation="false">
                                        <i class="icon-download"></i>&nbsp;&nbsp;<asp:label id="lblDownload" runat="server" Text="Download All"></asp:label>
                                    </asp:LinkButton>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:GridView ID="grvObject"runat="server"AllowPaging="true"PageSize="8"
                                        CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
                                        BorderWidth="1"AutoGenerateColumns="false"width="100%">
                                        <AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
                                        <HeaderStyle CssClass="GridStyle_HeaderStyle"/>
                                        <RowStyle CssClass="GridStyle_RowStyle"/>
                                        <pagerstyle cssclass="GridStyle_pagination"/>
                                        <Columns>
                                            <asp:TemplateField>
                                                <ItemStyleHorizontalAlign="Center"width="1%"/>
                                                <HeaderTemplate>
                                                    <asp:CheckBox ID="chkAll" runat="server"/>
                                                </HeaderTemplate>
                                                <ItemTemplate>
                                                    <asp:CheckBox ID="chkSelect"runat="server"/>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="Name" SortExpression="Name">
                                            <ItemTemplate>
                                                <asp:Label ID="lblFileName"Visible="false"runat="server"></asp:Label>
                                                <asp:Literal runat="server"ID="ltlFileItem"></asp:Literal>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:BoundField DataField="CreationTime" HeaderText="Creation Time" SortExpression="CreationTime" />
                                        <asp:BoundField DataField="LastWriteTime"HeaderText="Date Modified" SortExpression="LastWriteTime" />
                                        <asp:TemplateField HeaderText="Size"SortExpression="Size"ItemStyle-HorizontalAlign="Right">
                                            <ItemStyle HorizontalAlign="Right"></ItemStyle>
                                            <ItemTemplate>
                                                <%# DisplaySize(CType(Eval("Size"), Nullable(Of Long))) %>
                                            </ItemTemplate>
                                        </asp:TemplateField>                       
                                        </Columns>                               
                                    </asp:GridView>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </td>
        </tr>       
    </table>
</asp:Content>

- B4: Trong Visual Studio tạo 1 Class có tên: FileSystemItem và nhập đoạn Code phía dưới cho Class này.
C# Code
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;

public class FileSystemItem
{

    public FileSystemItem(FileInfofile)
    {
        this.Name = file.Name;
        this.FullName = file.FullName;
        this.Size = file.Length;
        this.CreationTime = file.CreationTime;
        this.LastAccessTime = file.LastAccessTime;
        this.LastWriteTime = file.LastWriteTime;
    }

    public string Name { get; set; }
    public stringFullName { get; set; }
    public Nullable<long> Size { get; set; }
    public DateTimeCreationTime { get; set; }
    public DateTimeLastAccessTime { get; set; }
    public DateTimeLastWriteTime { get; set; }
}
VB.NET Code
Imports System.IO

Public Class FileSystemItem

    Public Sub New(ByVal file As FileInfo)
        Me.Name = file.Name
        Me.FullName = file.FullName
        Me.Size = file.Length
        Me.CreationTime = file.CreationTime
        Me.LastAccessTime = file.LastAccessTime
        Me.LastWriteTime = file.LastWriteTime
    End Sub

    Public Property Name As String
    Public PropertyFullName As String
    Public Property Size As Nullable(Of Long)
    Public PropertyCreationTime As DateTime
    Public PropertyLastAccessTime As DateTime
    Public PropertyLastWriteTime As DateTime

End Class

B5: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;
using ICSharpCode.SharpZipLib.Zip;

namespace DownloadMultipleFiles
{
    public partial class _Default : System.Web.UI.Page
    {
        #region"Private Members"

        string FilePath = "";

        #endregion

        #region"Private Methods"

        private voidSetFilePath()
        {
            FilePath = MapPath("~/Upload/");
            if (!Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
            }
        }

        protected stringDisplaySize(long? size)
        {
            if (size == null)
                return string.Empty;
            else
            {
                if (size < 1024)
                    return string.Format("{0:N0} bytes", size.Value);
                else
                    return String.Format("{0:N0} KB", size.Value / 1024);
            }
        }   

        private stringGetFullyQualifiedFolderPath(string folderPath)
        {
            if (folderPath.StartsWith("~"))
            {
                return Server.MapPath(folderPath);
            }
            else
            {
                return folderPath;
            }
        }

        #endregion

        #region"GridView Methods"

        protected voidgrvObject_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgse)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                FileSystemItem item = (FileSystemItem)e.Row.DataItem;

                LabellblFileName = (Label)e.Row.FindControl("lblFileName");
                if (lblFileName != null)
                {
                    lblFileName.Text = item.FullName;
                }

                Literal ltlFileItem = (Literal)e.Row.FindControl("ltlFileItem");
                if (lblFileName != null)
                {
                    ltlFileItem.Text = item.Name;
                }
            }
        }

        #endregion

        #region"Bind Data"

        private voidBindData()
        {
            DirectoryInfo currentDirInfo = new DirectoryInfo(GetFullyQualifiedFolderPath(FilePath));
            dynamic folders = currentDirInfo.GetDirectories();
            dynamic files = currentDirInfo.GetFiles();

            var fsItems = new List<FileSystemItem>(folders.Length + files.Length);

            foreach (var file in files)
                fsItems.Add(new FileSystemItem(file));

            grvObject.DataSource = fsItems;
            grvObject.DataBind();
        }

        #endregion

        #region"Event Handles"

        protected voidPage_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    SetFilePath();
                    BindData();
                }
            }
            catch
            {
            }
        }

        private voidDownloadFile(string filepath)
        {
            if (!string.IsNullOrEmpty(filepath))
            {
                System.IO.FileInfo file = new System.IO.FileInfo(filepath);

                if (file.Exists)
                {
                    Response.Clear();
                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.BufferOutput = false;
                    Response.ContentType = "application/zip";
                    Response.AddHeader("content-disposition", "attachment; filename=" + file.Name);
                    Response.WriteFile(file.FullName);
                    file.Delete();
                    Response.End();
                }
                else
                {
                    Response.Write("This file does not exist.");
                }
            }
            else
            {
                Response.Write("Please provide a file to download.");
            }
        }

        protected voidcmdDownload_Click(object sender, System.EventArgs e)
        {
            try
            {
                SetFilePath();
                int intCount = grvObject.Rows.Count;
                CheckBox chkSelect = default(CheckBox);
                Label lblLabel = default(Label);
                int i = 0;

                if (intCount > 0)
                {
                    string sZipFileName = string.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HHmmss"));
                    ZipOutputStream s = new ZipOutputStream(File.Create(FilePath + "\\"+ sZipFileName));
                    s.SetLevel(9);

                    byte[] buffer = null;
                    buffer = new byte[4097];

                    for (i = 0; i <= intCount - 1; i++)
                    {
                        chkSelect = (CheckBox)grvObject.Rows[i].FindControl("chkSelect");
                        lblLabel = (Label)grvObject.Rows[i].FindControl("lblFileName");
                        if ((chkSelect != null) & (lblLabel != null))
                        {
                            string FileName = "";
                            if(lblLabel != null)
                            {
                                FileName = lblLabel.Text;
                            }

                            if (!string.IsNullOrEmpty(FileName) && chkSelect.Checked)
                            {
                                ZipEntry entry = newZipEntry(Path.GetFileName(FileName));
                                entry.DateTime = DateTime.Now;
                                s.PutNextEntry(entry);

                                FileStream fs = File.OpenRead(FileName);
                                int sourceBytes = 1;

                                while (!((sourceBytes <= 0)))
                                {
                                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                    s.Write(buffer, 0, sourceBytes);
                                }
                                fs.Close();
                            }
                        }
                    }
                    s.Finish();
                    s.Close();
                    DownloadFile(FilePath + "\\"+ sZipFileName);
                }
            }
            catch
            {
                return;
            }
            finally
            {
            }
        }

        #endregion
    }
}
VB.Net Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports System.IO
Imports ICSharpCode.SharpZipLib.Zip
Imports ICSharpCode.SharpZipLib.Checksums
Imports ICSharpCode.SharpZipLib.GZip

Namespace DownloadMultipleFiles

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Private Members"

        Private FilePath As String = ""

#End Region

#Region "Private Methods"

        Private Sub SetFilePath()
            FilePath = MapPath("~/Upload")
            If Not Directory.Exists(FilePath) Then
                Directory.CreateDirectory(FilePath)
            End If
        End Sub

        Protected FunctionDisplaySize(ByVal size AsNullable(Of Long)) As String
            If size Is Nothing Then
                Return String.Empty
            Else
                If size < 1024 Then
                    Return String.Format("{0:N0} bytes", size.Value)
                Else
                    Return String.Format("{0:N0} KB", size.Value / 1024)
                End If
            End If
        End Function

        Private FunctionGetFullyQualifiedFolderPath(ByVal folderPath As String) As String
            If folderPath.StartsWith("~") Then
                ReturnServer.MapPath(folderPath)
            Else
                Return folderPath
            End If
        End Function

#End Region

#Region "GridView Methods"

        Protected SubgrvObject_RowDataBound(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewRowEventArgs) Handles grvObject.RowDataBound
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim item AsFileSystemItem = CType(e.Row.DataItem, FileSystemItem)

                Dim lblFileName AsLabel = CType(e.Row.FindControl("lblFileName"), Label)
                If NotlblFileName Is NothingThen
                    lblFileName.Text = item.FullName
                End If

                Dim ltlFileItem AsLiteral = CType(e.Row.FindControl("ltlFileItem"), Literal)
                If NotlblFileName Is NothingThen
                    ltlFileItem.Text = item.Name
                End If
            End If
        End Sub

#End Region

#Region "Bind Data"

        Private SubBindData()
            Dim currentDirInfo AsNew DirectoryInfo(GetFullyQualifiedFolderPath(FilePath))
            Dim folders = currentDirInfo.GetDirectories()
            Dim files = currentDirInfo.GetFiles()

            Dim fsItems As New List(Of FileSystemItem)(folders.Length + files.Length)

            For Each file In files
                fsItems.Add(New FileSystemItem(file))
            Next

            grvObject.DataSource = fsItems
            grvObject.DataBind()
        End Sub

#End Region

#Region "Event Handles"

        Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If Page.IsPostBack = False Then
                    SetFilePath()
                    BindData()
                EndIf
            Catch ex As Exception

            End Try
        End Sub

        Private SubDownloadFile(ByVal filepath As String)
            If filepath <> ""Then
                Dim file AsNew System.IO.FileInfo(filepath)

                If file.Exists Then
                    Response.Clear()
                    Response.ClearContent()
                    Response.ClearHeaders()
                    Response.BufferOutput = False
                    Response.ContentType = "application/zip"
                    Response.AddHeader("content-disposition", "attachment; filename=" + file.Name)
                    Response.WriteFile(file.FullName)
                    file.Delete()
                    Response.End()
                Else
                    Response.Write("This file does not exist.")
                End If
            Else
                Response.Write("Please provide a file to download.")
            End If
        End Sub

        Private SubcmdDownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdDownload.Click
            Try
                SetFilePath()
                Dim intCount AsInteger = grvObject.Rows.Count
                Dim chkSelect AsCheckBox
                Dim lblLabel AsLabel
                Dim i AsInteger

                If intCount > 0 Then
                    Dim sZipFileName As String = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HHmmss"))
                    Dim s AsZipOutputStream = NewZipOutputStream(File.Create(FilePath & "\" & sZipFileName))
                    s.SetLevel(9)

                    Dim buffer() AsByte
                    ReDim buffer(4096)

                    For i = 0 TointCount - 1
                        chkSelect = CType(grvObject.Rows(i).FindControl("chkSelect"), CheckBox)
                        lblLabel = CType(grvObject.Rows(i).FindControl("lblFileName"), Label)
                        If Not chkSelect Is Nothing And Not lblLabel Is Nothing Then
                            DimFileName As String= ""
                            If Not lblLabel Is Nothing Then
                                FileName = lblLabel.Text
                            End If

                            If FileName <> ""AndAlso chkSelect.Checked Then
                                Dim entry As ZipEntry = New ZipEntry(Path.GetFileName(FileName))
                                entry.DateTime = DateTime.Now
                                s.PutNextEntry(entry)

                                Dimfs As FileStream= File.OpenRead(FileName)
                                Dim sourceBytes As Integer = 1

                                Do Until (sourceBytes <= 0)
                                    sourceBytes = fs.Read(buffer, 0, buffer.Length)
                                    s.Write(buffer, 0, sourceBytes)
                                Loop
                                fs.Close()
                            End If
                        End If
                    Next
                    s.Finish()
                    s.Close()
                    DownloadFile(FilePath & "\"& sZipFileName)
                End If
            Catch ex As Exception
                Exit Sub
            Finally

            End Try
        End Sub

#End Region

    End Class

End Namespace

Chạy Project, mỗi khi lựa chọn file và kích nút Download, toàn bộ các file được chọn sẽ được ZIP thành 1 file và Download về PC của người dùng.

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET




Chúc các bạn thành công!

Quang Bình

1 comments Blogger 1 Facebook

  1. Nhiều File Cho Một Lần Click Trong Asp.Net
    -
    Lập Trình Đốt Nét >>>>> Download Now

    >>>>> Download Full

    Nhiều File Cho Một Lần Click Trong Asp.Net
    -
    Lập Trình Đốt Nét >>>>> Download LINK

    >>>>> Download Now

    Nhiều File Cho Một Lần Click Trong Asp.Net
    -
    Lập Trình Đốt Nét >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete

 
lập trình đốt nét © 2013. All Rights Reserved. Powered by Blogger
Top