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


上傳文件有兩個主要的目的地,一個是服務器,另一個是數據庫,ASP.NET內置了FileUpload這個上傳控件,文本框顯示用戶選擇的文件的全名.

其屬性主要包括:

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

FileName:文件名稱

HasFile:是否選擇了文件

例子:
測試環境.net 2.0(內有詳細說明)

default.aspx

<%@ Page Language="C#" AutoEventWireup="true" 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">

<html xmlns="http://www.w3.org/1999/xhtml" > 
<head runat="server"> 
<title>無標題頁</title> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
<asp:FileUpload ID="FileUpload1" runat="server" /><br /> 
<br /> 
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="上傳" /> </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 (FileUpload1.HasFile)
        {
            //取得文件的擴展名,並轉換成小寫
            string fileExtension = System.IO.Path.GetExtension(FileUpload1.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)
            {
                resultlbl.Text = "要上傳的文件類型不對!";
            }

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

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

           }

        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM