(How to check image width and height before uploading in ASP.Net) – Bạn đang có một Hosting lưu trữ dữ liệu trên Server và cho phép người dùng Upload file ảnh lên đó. Tuy nhiên do không giới hạn kích thước file trước khi Upload lên dung lượng Hosting tăng lên nhanh chóng? Vậy làm sao để có thể kiểm tra kích thước hình ảnh trước khi tải lên Server? Bài viết dưới đây sẽ giúp bạn giải quyết dễ dàng vấn đề này,ngoài việc kiểm tra kích thước file ảnh, chương trình còn kiểm tra các định dạng file. Trong trường hợp không đúng định dạng file  hoặc quá dung lượng cho phép chương trình sẽ đưa ra cảnh báo.


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: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ PageTitle="How to check Image height and width before upload to the server in Asp.net"Language="C#"MasterPageFile="~/Site.master"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="CheckImageHeightWidthBeforeUpload._Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <table cellpadding="3"cellspacing="5"border="0"width="50%">
        <tr>
            <td>
                <divclass="panel panel-default">
                    <divclass="panel-heading">
                        <asp:label id="lblHeader" runat="server" Text="File Upload"></asp:label>
                    </div>
                    <divclass="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"OnServerValidate="valFile_ServerValidate"runat="server"CssClass="NormalRed"ValidationGroup="validate"ErrorMessage="You Must Upload A File" Display="Dynamic"></asp:CustomValidator>
                                             <asp:CustomValidator id="valType" OnServerValidate="valType_ServerValidate" runat="server"CssClass="NormalRed"ValidationGroup="validate"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>
                    <divclass="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.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

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

        #region"Private Members"

        private string FileFilter = "gif,jpg,jpeg,png,bmp,tif";
        private int Width = 150;
        private int Height = 150;

        #endregion

        #region"Event Handles"

        protected voidvalFile_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (FileUpload.PostedFile != null)
            {
                if (FileUpload.PostedFile.ContentLength > 0)
                {
                    args.IsValid = true;
                }
                else
                {
                    args.IsValid = false;
                }
            }
        }

        protected voidvalType_ServerValidate(System.Object source, System.Web.UI.WebControls.ServerValidateEventArgsargs)
        {
            try
            {
                int iWidth = 0;
                int iHeight = 0;
                lblMessage.Visible = false;

                if (FileUpload.PostedFile != null)
                {
                    if (FileUpload.PostedFile.ContentLength > 0)
                    {
                        string[] arr = FileUpload.PostedFile.FileName.Split(Convert.ToChar('.'));
                        string fileType = arr[arr.Length - 1].ToLower();

                        if(FileFilter.IndexOf(fileType) <= -1)
                        {
                            args.IsValid = false;
                            valType.ErrorMessage = "You must upload a file that is either a gif, jpg, jpeg, png, bmp, tif";
                            return;
                        }
                        else
                        {
                            System.Drawing.Image objImage = System.Drawing.Image.FromStream(FileUpload.PostedFile.InputStream);
                            if ((objImage != null))
                            {
                                iWidth = objImage.Width;
                                iHeight = objImage.Height;
                            }

                            if ((iWidth > Width) | (iHeight > Height))
                            {
                                args.IsValid = false;
                                valType.ErrorMessage = "Image Height and Width must not exceed 100px.";
                                return;
                            }
                            else
                            {
                                args.IsValid = true;
                                lblMessage.Text = "Valid";
                                lblMessage.ForeColor = System.Drawing.Color.Green;
                                lblMessage.Visible = true;
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
        #endregion
    }
}
VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports System.IO

Namespace CheckImageHeightWidthBeforeUpload

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Private Members"

        Private FileFilter AsString = "gif,jpg,jpeg,png,bmp,tif"
        Private Width As Integer = 150
        Private Height As Integer = 150

#End Region

#Region "Event Handles"

        Private SubvalFile_ServerValidate(ByVal source As System.Object, ByVal args AsSystem.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 SubvalType_ServerValidate(ByVal source As System.Object, ByVal args AsSystem.Web.UI.WebControls.ServerValidateEventArgs) Handles valType.ServerValidate
            Try
                Dim iWidth AsInteger = 0
                Dim iHeight AsInteger = 0
                lblMessage.Visible = False

                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()

                        If FileFilter <> ""And InStr(","& FileFilter.ToLower, ","& fileType.ToLower) = 0 Then
                            args.IsValid = False
                            valType.ErrorMessage = "You must upload a file that is either a gif, jpg, jpeg, png, bmp, tif"
                            Return
                        Else
                            Dim objImage AsSystem.Drawing.Image = System.Drawing.Image.FromStream(FileUpload.PostedFile.InputStream)
                            If Not objImage Is Nothing Then
                                iWidth = objImage.Width
                                iHeight = objImage.Height
                            End If
                         
                            If (iWidth > Width) Or(iHeight > Height) Then
                                args.IsValid = False
                                valType.ErrorMessage = "Image Height and Width must not exceed 100px."
                                Return
                            Else
                                args.IsValid = True
                                lblMessage.Text = "Valid"
                                lblMessage.ForeColor = System.Drawing.Color.Green
                                lblMessage.Visible = True
                            End If
                        End If
                    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 hoặc quá kích thước 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

0 comments Blogger 0 Facebook

Post a Comment

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