Kiểm soát kích thước file và thư mục Upload lên Server trong Asp.net
(Restrict the size of file upload in asp.net) – Khi xây dựng chức năng Upload file lên Server, khi không giới hạn dung lượng file nếu người dùng Upload file quá lớn trang Web thường hay xuất hiện lỗi. Vậy làm sao để có thể kiểm tra trước dung lượng file trước khi Upload lên Server?
Bài viết dưới đây sẽ giúp chúng ta giải quyết vấn đề kiểm soát kích thước file upload, nếu dung lượng file vượt quá cho phép một cảnh báo sẽ xuất hiện. Ngoài ra chương trình còn kiểm tra dung lượng thư mục (Folder), nếu thư mục còn dung lượng cho phép việc Upload file mới được thực hiện thành công.
- B1: Tạo Project trong Microsoft Visual Studio 2010
- B2: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
Bài viết dưới đây sẽ giúp chúng ta giải quyết vấn đề kiểm soát kích thước file upload, nếu dung lượng file vượt quá cho phép một cảnh báo sẽ xuất hiện. Ngoài ra chương trình còn kiểm tra dung lượng thư mục (Folder), nếu thư mục còn dung lượng cho phép việc Upload file mới được thực hiện thành công.
- B1: Tạo Project trong Microsoft Visual Studio 2010
- B2: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
C# Code
<%@ Page
Title="Restrict
the size of file uploads in ASP.NET" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RestrictSizeofFileUpload._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="Restrict the size of file uploads"></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:label id="lblAllowed"
runat="server"></asp:label><br />
<asp:CustomValidator id="valFile"
runat="server"
CssClass="NormalRed"
ValidationGroup="validate"
OnServerValidate="valFile_ServerValidate"
ErrorMessage="You
Must Upload A File" 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>
VB.NET Code
<%@ Page
Title="Restrict
the size of file uploads in ASP.NET" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="RestrictSizeofFileUpload._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="Restrict the size of file uploads"></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:label id="lblAllowed"
runat="server"></asp:label><br />
<asp:CustomValidator id="valFile"
runat="server"
CssClass="NormalRed"
ValidationGroup="validate"
ErrorMessage="You
Must Upload A File" 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" 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>- B3: 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;
using System.Web.UI.WebControls;
namespace RestrictSizeofFileUpload
{
public partial class _Default :
System.Web.UI.Page
{
#region
"Private Members"
private string
FilePath = "";
private long
RestrictFileSize = 2;
private long
RestrictFolderSize = 100;
#endregion
#region
"Private Methods"
public long
GetFolderSize(string DirPath, bool IncludeSubFolders = true)
{
DirectoryInfo objDir = new
DirectoryInfo(DirPath);
DirectoryInfo objFolder = null;
long
TotalSize = 0;
FileInfo objFileInfo = null;
foreach (FileInfo
objFileInfo_loopVariable in objDir.GetFiles())
{
objFileInfo = objFileInfo_loopVariable;
TotalSize += objFileInfo.Length;
}
if (IncludeSubFolders)
{
foreach (DirectoryInfo
objFolder_loopVariable in
objDir.GetDirectories())
{
objFolder = objFolder_loopVariable;
TotalSize +=
GetFolderSize(objFolder.FullName);
}
}
return TotalSize;
}
protected string
UploadFile(FileUpload file)
{
string fileName = null;
string fileExtension = "";
fileExtension = Path.GetExtension(file.FileName).Replace(".", "");
fileName = file.FileName.Substring(file.FileName.LastIndexOf("\\\\") + 1);
fileName = fileName.Substring(0, fileName.LastIndexOf(fileExtension)) +
fileExtension;
FilePath = FilePath + fileName;
file.SaveAs(FilePath);
return fileName;
}
private void
SetFilePath()
{
FilePath = MapPath("~/Upload/");
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
}
#endregion
#region
"Event Handles"
protected void
Page_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
lblAllowed.Text = "Allowed only
max " + RestrictFileSize + " MB to upload";
}
}
catch
{
}
}
protected void
cmdUpload_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
try
{
SetFilePath();
if (FileUpload.HasFile)
{
long FolderSize = 0;
FolderSize =
(GetFolderSize(FilePath, true) / 1024) / 1024;
if (FolderSize < RestrictFolderSize)
{
//1MB=1024KB
long filesize =
((FileUpload.PostedFile.ContentLength) / 1024) / 1024;
if (filesize < RestrictFileSize)
{
UploadFile(FileUpload);
lblMessage.Text
= "File uploaded successfully.";
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Visible = true;
}
else
{
lblMessage.Text
= "You are allowed to upload more then "
+ RestrictFileSize + " MB.";
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Visible = true;
}
}
else
{
lblMessage.Text = "The File Exceeds The Amount Of Disk Space You
Currently Have Available.";
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Visible
= true;
}
}
}
catch
{
}
}
}
protected void
valFile_ServerValidate(object source, ServerValidateEventArgs args)
{
if (FileUpload.PostedFile != null)
{
if (FileUpload.PostedFile.ContentLength
> 0)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
}
#endregion
}
}
VB.NET Code
'Visit http://www.laptrinhdotnet.com
for more ASP.NET Tutorials
Imports System.IO
Namespace RestrictSizeofFileUpload
Public Class _Default
Inherits System.Web.UI.Page
#Region "Private
Members"
Private FilePath As String = ""
Private RestrictFileSize As
Long = 2
Private RestrictFolderSize As
Long = 100
#End Region
#Region "Private
Methods"
Function GetFolderSize(ByVal
DirPath As String,
Optional ByVal
IncludeSubFolders As Boolean
= True) As Long
Dim objDir As DirectoryInfo = New
DirectoryInfo(DirPath)
Dim objFolder As DirectoryInfo
Dim TotalSize As Long
Dim
objFileInfo As FileInfo
For Each objFileInfo In objDir.GetFiles()
TotalSize += objFileInfo.Length
Next
If IncludeSubFolders Then
For Each
objFolder In objDir.GetDirectories()
TotalSize += GetFolderSize(objFolder.FullName)
Next
End If
Return TotalSize
End Function
Protected Function
UploadFile(ByVal file As
FileUpload) As
String
Dim fileName As String
Dim fileExtension As String = ""
fileExtension = Replace(Path.GetExtension(file.FileName),
".", "")
fileName = file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1)
fileName = fileName.Substring(0,
fileName.LastIndexOf(fileExtension)) & fileExtension
FilePath = FilePath + fileName
file.SaveAs(FilePath)
Return fileName
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"
Protected Sub
Page_Load(ByVal sender As
Object, ByVal e
As System.EventArgs)
Handles Me.Load
Try
If Page.IsPostBack = False Then
lblAllowed.Text = "Allowed only
max " & RestrictFileSize
& " MB to upload"
End If
Catch ex As Exception
End Try
End Sub
Private Sub
cmdUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdUpload.Click
If Page.IsValid Then
Try
SetFilePath()
If FileUpload.HasFile Then
Dim FolderSize As Long
FolderSize =
(GetFolderSize(FilePath, True) / 1024) / 1024
If FolderSize < RestrictFolderSize Then
'1MB=1024KB
Dim filesize As Long = ((FileUpload.PostedFile.ContentLength) / 1024)
\ 1024
If filesize < RestrictFileSize Then
UploadFile(FileUpload)
lblMessage.Text
= "File uploaded successfully."
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Visible = True
Else
lblMessage.Text
= "You are allowed to upload more then "
& RestrictFileSize & " MB."
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Visible = True
End If
Else
lblMessage.Text = "The File Exceeds The Amount Of Disk Space You
Currently Have Available."
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Visible
= True
End If
End If
Catch ex As
Exception
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
#End Region
End Class
End Namespace
Chúc các bạn thành công!
Quang Bình
No Comment to " Kiểm soát kích thước file và thư mục Upload lên Server trong Asp.net "