News Ticker

Menu

Sử dụng CustomValidator để kiểm tra kiểu file khi Upload trong Asp.net

(How to Check File Type UsingCustomValidator in ASP.Net) – FileUpload là Control giúp người lập trình dễ dàng thực hiện chức năng Upload file lên Server. Tuy nhiên khi sử dụng mặc định Control này người lập trình không kiểm soát được các kiểu file cho người sử dụng Upload. Do đó người sử dụng dễ dàng Upload cả những file mà mình không mong muốn. Vậy có cách nào để có thể kiểm soát việc này không? Bài viết dưới đây sẽ giúp bạn giải quyết dễ dàng vấn đề này.

Xem những Video hay dành cho thiếu nhi - 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: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML
<%@ Page Title="How to Check File Type UsingCustomValidator in ASP.Net" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckFileTypeUsingCustomValidator._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" ValidationGroup="validate" Causesvalidation="true">
                                <i class="icon-upload"></i>&nbsp;&nbsp;<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.UI.WebControls;

namespace CheckFileTypeUsingCustomValidator
{

    public partial class _Default : System.Web.UI.Page
    {

        #region "Private Members"

        private string FileFilter = "gif,jpg,jpeg,png,doc,docx,xls,xlsx,ppt,pptx,rar,zip,pdf";

        #endregion

        #region "Event Handles"

        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 JPG, JPEG, GIF, PNG, ZIP, ZAR, DOC, DOCX, XLS, XLSX, PPT, PPTX, PDF";
                    if (FileFilter.IndexOf(FileType)>-1)
                    {
                        args.IsValid = true;
                        lblMessage.Text = "Valid";
                        lblMessage.ForeColor = System.Drawing.Color.Green;
                        lblMessage.Visible = true;
                    }
                    else
                    {
                        args.IsValid = false;
                        lblMessage.Text = "InValid";
                        lblMessage.ForeColor = System.Drawing.Color.Red;
                        lblMessage.Visible = true;
                    }
                }
                else
                {
                    args.IsValid = false;
                }
            }
        }

        #endregion
    }
}
VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials

Namespace CheckFileTypeUsingCustomValidator

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Private Members"

        Private FileFilter As String = "gif,jpg,jpeg,png,doc,docx,xls,xlsx,ppt,pptx,rar,zip,pdf"

#End Region

#Region "Event Handles"

        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 JPG, JPEG, GIF, PNG, ZIP, ZAR, DOC, DOCX, XLS, XLSX, PPT, PPTX, PDF"
                        If FileFilter <> "" And Not InStr("," & FileFilter.ToLower, "," & fileType.ToLower) = 0 Then
                            args.IsValid = True
                            lblMessage.Text = "Valid"
                            lblMessage.ForeColor = System.Drawing.Color.Green
                            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 nằm trong danh sách không cho phép phần mềm sẽ đưa ra thông báo cho người sử dụng biết.

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

Share This:

Post Tags:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Sử dụng CustomValidator để kiểm tra kiểu file khi Upload trong Asp.net "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM