Download nhiều file cho một lần Click trong Asp.net
(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 đó.
- 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
<%@ Page
Title="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>
<div
class="panel
panel-default">
<div
class="panel-heading">
<asp:label id="lblHeader" runat="server" Text="Download Multiple Files"></asp:label>
</div>
<div
class="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> <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">
<AlternatingRowStyle
CssClass="GridStyle_AltRowStyle"
/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"
/>
<RowStyle CssClass="GridStyle_RowStyle"
/>
<pagerstyle cssclass="GridStyle_pagination"
/>
<Columns>
<asp:TemplateField>
<ItemStyle
HorizontalAlign="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>
<%@ Page
Title="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>
<div
class="panel
panel-default">
<div
class="panel-heading">
<asp:label id="lblHeader" runat="server" Text="Download Multiple Files"></asp:label>
</div>
<div
class="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> <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%">
<AlternatingRowStyle
CssClass="GridStyle_AltRowStyle"
/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"
/>
<RowStyle CssClass="GridStyle_RowStyle"
/>
<pagerstyle cssclass="GridStyle_pagination"
/>
<Columns>
<asp:TemplateField>
<ItemStyle
HorizontalAlign="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(FileInfo
file)
{
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 string
FullName { get; set;
}
public Nullable<long> Size { get; set; }
public DateTime
CreationTime { get; set;
}
public DateTime
LastAccessTime { get; set;
}
public DateTime
LastWriteTime { get; set;
}
}
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 Property
FullName As String
Public Property Size As Nullable(Of Long)
Public Property
CreationTime As DateTime
Public Property
LastAccessTime As DateTime
Public Property
LastWriteTime 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 void
SetFilePath()
{
FilePath = MapPath("~/Upload/");
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
}
protected string
DisplaySize(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 string
GetFullyQualifiedFolderPath(string folderPath)
{
if (folderPath.StartsWith("~"))
{
return Server.MapPath(folderPath);
}
else
{
return folderPath;
}
}
#endregion
#region
"GridView Methods"
protected void
grvObject_RowDataBound(object sender,
System.Web.UI.WebControls.GridViewRowEventArgs
e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
FileSystemItem item = (FileSystemItem)e.Row.DataItem;
Label
lblFileName = (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 void
BindData()
{
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 void
Page_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
SetFilePath();
BindData();
}
}
catch
{
}
}
private void
DownloadFile(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 void
cmdDownload_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 = new
ZipEntry(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
}
}
'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 Function
DisplaySize(ByVal size As
Nullable(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 Function
GetFullyQualifiedFolderPath(ByVal folderPath As String) As String
If folderPath.StartsWith("~")
Then
Return
Server.MapPath(folderPath)
Else
Return folderPath
End If
End Function
#End Region
#Region "GridView
Methods"
Protected Sub
grvObject_RowDataBound(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewRowEventArgs)
Handles grvObject.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow
Then
Dim item As
FileSystemItem = CType(e.Row.DataItem,
FileSystemItem)
Dim lblFileName As
Label = CType(e.Row.FindControl("lblFileName"), Label)
If Not
lblFileName Is Nothing
Then
lblFileName.Text = item.FullName
End If
Dim ltlFileItem As
Literal = CType(e.Row.FindControl("ltlFileItem"), Literal)
If Not
lblFileName Is Nothing
Then
ltlFileItem.Text = item.Name
End If
End If
End Sub
#End Region
#Region "Bind Data"
Private Sub
BindData()
Dim currentDirInfo As
New 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 Sub
Page_Load(ByVal sender As
Object, ByVal e
As System.EventArgs)
Handles Me.Load
Try
If Page.IsPostBack = False Then
SetFilePath()
BindData()
End
If
Catch ex As Exception
End Try
End Sub
Private Sub
DownloadFile(ByVal filepath As String)
If filepath <> ""
Then
Dim file As
New 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 Sub
cmdDownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdDownload.Click
Try
SetFilePath()
Dim intCount As
Integer = grvObject.Rows.Count
Dim chkSelect As
CheckBox
Dim lblLabel As
Label
Dim i As
Integer
If intCount > 0 Then
Dim sZipFileName As String = String.Format("Zip_{0}.zip",
DateTime.Now.ToString("yyyy-MM-dd-HHmmss"))
Dim s As
ZipOutputStream = New
ZipOutputStream(File.Create(FilePath
& "\" & sZipFileName))
s.SetLevel(9)
Dim buffer() As
Byte
ReDim buffer(4096)
For i = 0 To
intCount - 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
Dim
FileName 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)
Dim
fs 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.
Chúc các bạn thành công!
Quang Bình
No Comment to " Download nhiều file cho một lần Click trong Asp.net "