拖一个FileUpload控件,设计如图:
查看源:
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="UploadFile" runat="server" />
<br />
<asp:Button ID="btnSave" runat="server" Text="Save" οnclick="btnSave_Click" />
<asp:Button ID="btnDisplay" runat="server" Text="Display"
οnclick="btnDisplay_Click" />
<br />
<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
<asp:Label ID="lblDisplay" runat="server"></asp:Label>
</div>
</form>
</body>
双击Save按扭,在打开后置的cs文件:
在F盘新建一个文件夹Uploads:
protected void btnSave_Click(object sender, EventArgs e)
{
string str = "";
if (UploadFile.HasFile)
{//检测文本框中是否输入了有效的完全限定文件名
try
{
//获取客户端使用的文件名称
str += "Uploading file:" + UploadFile.FileName;
//将上传的文件保存到web服务器指定路径
//返回与web服务器上虚拟路径的相对物理路径
UploadFile.SaveAs("F:\\Uploads\\" + UploadFile.FileName);
//文件名称
str += "<br/>Saves As:" + UploadFile.PostedFile.FileName;
//文件类型
str += "<br/>File Type:" + UploadFile.PostedFile.ContentType;
//文件大小
str += "<br/>File Length(bytes):" + UploadFile.PostedFile.ContentLength;
str += "<br/>PostedFile File Name:" + UploadFile.PostedFile.FileName;
//UploadFile.SaveAs("F:\\Uploads\\" + UploadFile.FileName);
//lblMessage.Text = "File name: " +
//UploadFile.PostedFile.FileName + "<br>" +
//UploadFile.PostedFile.ContentLength + " kb<br>" +
//"Content type: " +
//UploadFile.PostedFile.ContentType;
}
catch (Exception ex)
{
str += "<br/><b>Error</b><br/>Unable to save UpLoad/" + UploadFile.FileName + "<br/>" + ex.Message;
//lblMessage.Text = "ERROR: " + ex.Message.ToString();
}
}
else
{
str = "No File uploaded";
//lblMessage.Text = "You have not specified a file.";
}
lblMessage.Text = str;
lblDisplay.Text = "";
}
双击Display按钮:
//显示所选的文件,显示文件的所有内容
protected void btnDisplay_Click(object sender, EventArgs e)
{
string str = "<u>File:" + UploadFile.FileName + "<u><br/>";
if (UploadFile.HasFile)
{//检测文本框中是否输入了有效的完全限定文件名
try
{
Stream stream = UploadFile.FileContent;
//读取字符
StreamReader reader = new StreamReader(stream);
string strLine = "";
do
{
//读取一行并将数据作为字符串返回
strLine = reader.ReadLine();
str += strLine;
} while (strLine != null);
}
catch (Exception ex)
{
str += "<br/><b>Error</b><br/> Unable to display" + UploadFile.FileName + "<br/>" + ex.Message;
}
}
else
{
str = "No file uploaded";
}
lblMessage.Text = str;
lblDisplay.Text = "";
}