<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="测试.WebForm1" %>
<!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>
<table style="width: 90%">
<tr>
<td style="width: 159px" colspan=2>
<strong><span style="font-size: 10pt">最简单的单文件上传</span></strong></td>
</tr>
<tr>
<td style="width: 600px">
<asp:FileUpload ID="FileUpload1" runat="server" Width="600px" /></td>
<td align=left>
<asp:Button ID="FileUpload_Button" runat="server" Text="上传图片" OnClick="FileUpload_Button_Click" /></td>
</tr>
<tr>
<td colspan=2>
<asp:Label ID="Upload_info" runat="server" ForeColor="Red" Width="767px"></asp:Label></td>
</tr>
</table>
</div>
</form>
</body>
</html>
//后置代码
using System;
using System.Data;
using System.Configuration;
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 FileUpload_Button_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.PostedFile.FileName == "")
//if (FileUpload1.FileName == "")
//if (!FileUpload1.HasFile) //获取一个值,该值指示 System.Web.UI.WebControls.FileUpload 控件是否包含文件。包含文件,则为 true;否则为 false。
{
this.Upload_info.Text = "请选择上传文件!";
}
else
{
string filepath = FileUpload1.PostedFile.FileName; //得到的是文件的完整路径,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg
//string filepath = FileUpload1.FileName; //得到上传的文件名20022775_m.jpg
string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg
string serverpath = Server.MapPath("~/images/") + filename;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg
FileUpload1.PostedFile.SaveAs(serverpath);//将上传的文件另存为
this.Upload_info.Text = "上传成功!";
}
}
catch (Exception ex)
{
this.Upload_info.Text = "上传发生错误!原因是:" + ex.ToString();
}
}
}
后置代码找不到的就是前置代码的标签,可我声明为服务器控件了,为什么还是不行,特别不明白。谢谢各位大佬。