FileUpload檢查上傳文件擴展名,限制大小,創建路徑存儲


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="up" %>

<!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" /> 
<input id="Button1" runat="server" onserverclick="Button1_ServerClick" type="button"
value="上傳" /></div>
</form>
</body>
</html>

//Code:
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;
using System.IO;

public partial class up : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_ServerClick(object sender, EventArgs e)
{
//取得字符串:“C:\Documents and Settings\Administrator\Desktop\picture\213.jpg”
string fileName = this.FileUpload1.PostedFile.FileName;
//取得從開始到最后一個“\”得長度:fileName.LastIndexOf("\\")
int length = fileName.Length - fileName.LastIndexOf("\\") - 1;
//截取從fileName.LastIndexOf("\\") + 1位置到length位置的字符串
fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1, length);
//取得字符串:“C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite1\upload2\”
string path = Server.MapPath("upload2\\");
//判斷有沒有path的文件,如果沒有則創建一個新的
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
//取得文件的后綴名:“.jpg ”
string s1 = System.IO.Path.GetExtension(fileName);
//取得Web.Config中 <appSettings><add key="conn" value="2048"/></appSettings>配置的值
string s2=System.Configuration.ConfigurationManager.AppSettings["conn"];
//取得上傳的文件的大小,單位為bytes
int filesize = (FileUpload1.PostedFile.ContentLength) / 1024;
if ( s1 == ".jpg" || s1 == ".gif")
{
//如果文件大小<設定大小,則上傳文件到:C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite1\upload2\213.jpg
if (filesize < Convert.ToInt32(s2))
{
FileUpload1.PostedFile.SaveAs(path + fileName);
}
else
{
Response.Write("<script>alert('太大了')</script>");
}
}
else
{
Response.Write("<script>alert('請選擇JPG或GIF格式的文件')</script>");
}
}
}


免責聲明!

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



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