Sử dụng SharpZipLib để Upload 1 lần nhiều file trong Asp.net
(Using SharpZipLib to unzip specific files in ASP.Net) –Mặc định Control FileUpload chỉ cho phép người dùng mỗi lần Upload chỉ 1 file. Trong trường hợp có nhiều file thì việc Upload này sẽ mất nhiều thời gian để thực hiện công việc này. Vậy có cách nào để vẫn sử dụng Control FileUpload mà có thể Upload nhiều file cho 1 lần thực hiện không? Bài viết dưới đây sẽ hướng dẫn các bạn sử dụng SharpZipLib để Upload 1 lần nhiều file. Chỉ cần ZIP tất cả các file vào 1 file ZIP và thực hiện Upload là toàn bộ các file sẽ được đẩy lên Server.
- 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
<%@ Page
Title="How to
extract a folder from zip file using SharpZipLib in ASP.Net" Language="C#"
MasterPageFile="~/Site.master"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
Inherits="UsingSharpZipLibUnzipFile._Default"
%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table cellpadding="3"
cellspacing="5"
border="0"
width="50%">
<tr>
<td>
<div
class="panel
panel-default">
<div
class="panel-heading">
<asp:label id="lblHeader" runat="server" Text="File Upload"></asp:label>
</div>
<div
class="panel-body">
<table cellspacing="2" cellpadding="3" border="0" width="100%">
<tr>
<td style="width:25%;">
<asp:label id="plFileName"
runat="server"
Text="File Name
(*)"></asp:label>
</td>
<td>
<asp:FileUpload ID="FileUpload"
runat="server"
Width="150px"
/><br />
<asp:CustomValidator id="valFile"
runat="server"
CssClass="NormalRed"
ValidationGroup="validate"
OnServerValidate="valFile_ServerValidate"
ErrorMessage="You
Must Upload A File" Display="Dynamic"></asp:CustomValidator>
<asp:CustomValidator id="valType" runat="server" CssClass="NormalRed" ValidationGroup="validate" OnServerValidate="valType_ServerValidate" Display="Dynamic"></asp:CustomValidator>
</td>
</tr>
<tr>
<td colspan="2">
<asp:label id="lblMessage"
runat="server"
Visible="false"></asp:label><br />
</td>
</tr>
</table>
</div>
<div
class="modal-footer">
<div class="btn-group">
<asp:LinkButton id="cmdUpload"
runat="server"
CssClass="btn
btn-small" OnClick="cmdUpload_Click" ValidationGroup="validate" Causesvalidation="true">
<i class="icon-upload"></i> <asp:label id="lblUpload" runat="server" Text="Upload"></asp:label>
</asp:LinkButton>
</div>
</div>
</div>
</td>
</tr>
</table>
</asp:Content>
- B4: 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 UsingSharpZipLibUnzipFile
{
public partial class _Default :
System.Web.UI.Page
{
#region
"Private Members"
string FilePath = "";
#endregion
#region
"Private Methods"
private string
ExtractFileName(string path)
{
int extractPos = path.LastIndexOf("\\") + 1;
return path.Substring(extractPos, path.Length -
extractPos).Replace("/", "_").Replace("..",
".");
}
private void
SetFilePath()
{
FilePath = MapPath("~/Upload/");
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
}
#endregion
#region
"Event Handles"
protected void
cmdUpload_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
try
{
ZipInputStream objZipInputStream = new ZipInputStream(FileUpload.PostedFile.InputStream);
ZipEntry objZipEntry =
objZipInputStream.GetNextEntry();
string strFileName = Path.GetFileName(FileUpload.FileName);
string strContentType =
FileUpload.PostedFile.ContentType;
int fileSize = FileUpload.PostedFile.ContentLength;
SetFilePath();
while (objZipEntry != null)
{
FileStream objFileStream = File.Create(FilePath
+ "zip_" +
ExtractFileName(objZipEntry.Name));
int intSize = 2048;
byte[] arrData = new byte[2049];
intSize =
objZipInputStream.Read(arrData, 0, arrData.Length);
if (intSize > 0)
{
while (intSize > 0)
{
objFileStream.Write(arrData, 0, intSize);
intSize =
objZipInputStream.Read(arrData, 0, arrData.Length);
}
objFileStream.Close();
string fileName = "";
fileName =
objZipEntry.Name;
if (File.Exists(FilePath
+ fileName))
{
for (int i = 1; i
<= 1000; i++)
{
if (!(File.Exists(FilePath
+ i.ToString() + "_" + fileName)))
{
fileName = i.ToString() + "_"
+ fileName;
break;
}
}
}
File.Copy(FilePath + "zip_"
+ objZipEntry.Name, FilePath + fileName);
File.Delete(FilePath + "zip_"
+ ExtractFileName(objZipEntry.Name));
objZipEntry =
objZipInputStream.GetNextEntry();
}
else
{
break;
}
}
objZipInputStream.Close();
}
catch
{
lblMessage.Text = "Upload file
Error";
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Visible = true;
}
finally
{
lblMessage.Text = "Upload file Sucessfully";
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Visible = true;
}
}
}
protected void
valFile_ServerValidate(object source, ServerValidateEventArgs args)
{
if (FileUpload.PostedFile != null)
{
if (FileUpload.PostedFile.ContentLength
> 0)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
}
protected void
valType_ServerValidate(object source, ServerValidateEventArgs args)
{
if (FileUpload.PostedFile != null)
{
if (FileUpload.PostedFile.ContentLength
> 0)
{
string [] arr =
FileUpload.PostedFile.FileName.Split(Convert.ToChar('.'));
string FileType =
arr[arr.Length-1].ToLower();
valType.ErrorMessage = "You must upload
a file that is either a ZIP";
if (FileType.ToLower() == "zip")
{
args.IsValid = true;
lblMessage.Text = "InValid";
lblMessage.ForeColor =
System.Drawing.Color.Green;
lblMessage.Visible = true;
}
else
{
args.IsValid = false;
}
}
else
{
args.IsValid = false;
}
}
}
#endregion
}
}
'Visit http://www.laptrinhdotnet.com
for more ASP.NET Tutorials
Imports System.IO
Imports ICSharpCode.SharpZipLib.Zip
Namespace UsingSharpZipLibUnzipFile
Public Class _Default
Inherits System.Web.UI.Page
#Region "Private
Members"
Private FileFilter As
String = "zip"
Private FilePath As String = ""
#End Region
#Region "Private
Methods"
Private Function
ExtractFileName(ByVal path As String) As String
Dim extractPos As Integer = path.LastIndexOf("\")
+ 1
Return path.Substring(extractPos, path.Length -
extractPos).Replace("/", "_").Replace("..",
".")
End Function
Private Sub
SetFilePath()
FilePath = MapPath("~/Upload/")
If Not Directory.Exists(FilePath) Then
Directory.CreateDirectory(FilePath)
End If
End Sub
#End Region
#Region "Event
Handles"
Private Sub
cmdUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdUpload.Click
If Page.IsValid Then
Try
Dim objZipInputStream As New ZipInputStream(FileUpload.PostedFile.InputStream)
Dim objZipEntry As
ZipEntry = objZipInputStream.GetNextEntry
Dim strFileName As
String = Path.GetFileName(FileUpload.FileName)
Dim strContentType As String =
FileUpload.PostedFile.ContentType
Dim fileSize As
Integer = FileUpload.PostedFile.ContentLength
SetFilePath()
While Not
objZipEntry Is Nothing
Dim objFileStream As FileStream = File.Create(FilePath
& "zip_" &
ExtractFileName(objZipEntry.Name))
Dim intSize As Integer = 2048
Dim
arrData(2048) As Byte
intSize =
objZipInputStream.Read(arrData, 0, arrData.Length)
If intSize > 0 Then
While intSize > 0
objFileStream.Write(arrData, 0, intSize)
intSize =
objZipInputStream.Read(arrData, 0, arrData.Length)
End While
objFileStream.Close()
Dim fileName As String = ""
fileName =
objZipEntry.Name
If File.Exists(FilePath
& fileName) Then
For i As Integer = 1 To 1000
If Not (File.Exists(FilePath & i.ToString() & "_" & fileName)) Then
fileName = i.ToString() & "_"
& fileName
Exit For
End If
Next
End If
File.Copy(FilePath & "zip_"
& objZipEntry.Name, FilePath & fileName)
File.Delete(FilePath & "zip_" & ExtractFileName(objZipEntry.Name))
objZipEntry =
objZipInputStream.GetNextEntry
Else
Exit While
End If
End While
objZipInputStream.Close()
Catch ex As
Exception
lblMessage.Text = ex.Message
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Visible = True
Finally
lblMessage.Text = "Upload file
Sucessfully"
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Visible = True
End Try
End If
End Sub
Private Sub
valFile_ServerValidate(ByVal source As System.Object, ByVal args As
System.Web.UI.WebControls.ServerValidateEventArgs)
Handles valFile.ServerValidate
Try
If Not
(FileUpload.PostedFile Is Nothing) Then
If (FileUpload.PostedFile.ContentLength
> 0) Then
args.IsValid = True
Return
End If
End If
args.IsValid = False
Catch exc As Exception
End Try
End Sub
Private Sub
valType_ServerValidate(ByVal source As System.Object, ByVal args As
System.Web.UI.WebControls.ServerValidateEventArgs)
Handles valType.ServerValidate
Try
If Not
(FileUpload.PostedFile Is Nothing) Then
If (FileUpload.PostedFile.ContentLength
> 0) Then
Dim arr As String() = FileUpload.PostedFile.FileName.Split(Convert.ToChar("."))
Dim fileType As String = arr(arr.Length - 1).ToLower()
valType.ErrorMessage = "You must upload a file that is either a ZIP"
If fileType.ToLower = "zip"
Then
args.IsValid = True
lblMessage.Text = "InValid"
lblMessage.ForeColor =
System.Drawing.Color.Red
lblMessage.Visible
= True
Return
End If
args.IsValid = False
End If
End If
Catch exc As Exception
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 Upload nếu định dạng file không phải là ZIP phần mềm sẽ đưa ra thông báo cho người sử dụng biết. Trong trường hợp file Upload là ZIP, phần mềm sẽ tự động UnZip các file trong file ZIP lên Server.
Chúc các bạn thành công!
Quang Bình
No Comment to " Sử dụng SharpZipLib để Upload 1 lần nhiều file trong Asp.net "