文件上傳前的判斷

ASP.NET(C#)FileUpload實現上傳限定類型和大小的文件

 (2010-05-14 13:23:01)ASP.NET內置了FileUpload這個上傳控件.html

其屬性主要包括:spa

ContenLength:上傳文件大小,單位:字節orm

FileName:文件名稱server

HasFile:是否選擇了文件xml

SaveAs():保存上傳文件的內容htm

default.aspx圖片

<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %>文件上傳

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">string

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>文件上傳功能</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload" runat="server" />
<br/>
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="上傳" />it

<br/>

<asp:Label ID="labresult" runat="server"></asp:Label> </div>
</form>
</body>
</html>

 

 

default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        Boolean fileOk = false;
        string path = Server.MapPath("~/upload/");


        //判斷是否已經選取文件
        if (FileUpload.HasFile)
        {
            //取得文件的擴展名,並轉換成小寫
            string fileExtension = System.IO.Path.GetExtension(FileUpload.FileName).ToLower();
            //限定只能上傳jpg和gif圖片
            string[] allowExtension = { ".jpg", ".gif", ".txt", ".xls" };
            //對上傳的文件的類型進行一個個匹對
            for (int i = 0; i < allowExtension.Length; i++)
            {
                if (fileExtension == allowExtension[i])
                {
                    fileOk = true;
                    break;
                }
            }            
            if (fileOk)
            {
                labresult.Text = "要上傳的文件類型不對!";
            }

            //對上傳文件的大小進行檢測,限定文件最大不超過2M
            if (FileUpload.PostedFile.ContentLength > 2048000)
            {
                fileOk = false;
            }
            //最後的結果
            if (fileOk)
            {
                try
                {
                    FileUpload.PostedFile.SaveAs(path + FileUpload.FileName);
                    labresult.Text ="上傳成功";
                }
                catch
                {

                    labresult.Text = "上傳失敗";
                }
            }
            else
            {
                 labresult.Text = "文件類型或者文件大小超出2M或者文件類型不對";

           }

        }     } }

相關文章
相關標籤/搜索