|
|
|
|
|
Asp.net
文件上传的实例
|
<%@ page Language = "C#" debug = "true" %>
<%@ Import Namespace = "System.IO" %>
<script language = "C#" runat = "server">
public void uploadFile(object sender , EventArgs E) {
//检查上传文件不为空
if(inputFile.PostedFile.ContentLength > 0) {
//设定上传文件的保存路径
string strSaveDir = "./upload/";
string strName = inputFile.PostedFile.FileName;
//取得文件名(抱括路径)里最后一个"."的索引
int intExt = strName.LastIndexOf(".");
//取得文件扩展名
string strExt = strName.Substring(intExt);
//这里我自动根据日期和文件大小不同为文件命名,确保文件名不重复
/*
DateTime datNow = DateTime.Now;
string strNewName = datNow.DayOfYear.ToString() + inputFile.PostedFile.ContentLength.ToString() + strExt;
*/
//取得文件名(包括路径)里最后一个"\"的索引
int intPath = strName.LastIndexOf("\\");
//取得文件名(不包括路径)
string strNewName = strName.Substring(intPath);
//保存文件到你所要的目录,这里是IIS根目录下的upload目录.你可以改变.
//注意: 我这里用Server.MapPath()取当前文件的绝对目录.在asp.net里"\"必须用"\\"代替
inputFile.PostedFile.SaveAs(Server.MapPath(strSaveDir + strNewName));
//得到这个文件的相关属性:文件名,文件类型,文件大小
labelUpResult.Text = "上传成功!";
labelFileName.Text = "文件源:" + strName;
labelFileExt.Text = "文件类型:" + inputFile.PostedFile.ContentType + "( " + strExt + " )";
labelFileSize.Text = "文件大小:" + (inputFile.PostedFile.ContentLength / 1024).ToString() + " K Byte(s)";
} else {
labelUpResult.Text = "请选择你要上传的文件!";
labelFileName.Text = "";
labelFileExt.Text = "";
labelFileSize.Text = "";
}
}
</script>
<html>
<head>
<title>上传文件</title>
</head>
<body>
<div align="center">
<table width="100%" border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#eeeeee" id="AutoNumber1">
<form id="formFile" method="post" action="" enctype="multipart/form-data" runat="server">
<tr>
<td align="center">
<input type="file" id="inputFile" name="inputFile" runat="server" size="64">
</td>
</tr>
<tr>
<td align="center">
<input type="button" value="Upload" OnServerClick="uploadFile" id="Button1" name="Button1" runat="server">
</td>
</tr>
<tr>
<td align="center">
<asp:Label id="labelUpResult" runat="server" text="" font-bold="True" forecolor="#FF0000"/><br>
<asp:Label id="labelFileName" runat="server" text="" font-bold="True" forecolor="#FF0000"/><br>
<asp:Label id="labelFileExt" runat="server" text="" font-bold="True" forecolor="#FF0000"/><br>
<asp:Label id="labelFileSize" runat="server" text="" font-bold="True" forecolor="#FF0000"/><br>
</td>
</tr>
</form>
</table>
</div>
</body>
</html>
|
|
|
|
|