037. asp.netWeb用户控件之五使用用户控件实现文件上传功能

fileUpload.ascx代码:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="fileUpload.ascx.cs" Inherits="fileUpload" %>
<style type="text/css">
.style3
{
width: 196px;
}
.style4
{
width: 507px;
height: 269px;
}
.style5
{
width: 82%;
}
.style6
{
height: 180px;
}
.style7
{
width: 102px;
text-align: right;
}
</style>
<table align="left" cellpadding="0" cellspacing="0" class="style4"
style="background-image: url('upload.JPG')">
<tr>
<td valign="top">
<table align="center" cellpadding="0" cellspacing="0" class="style5"
style="font-size: small">
<tr>
<td class="style6" colspan="3">
</td>
</tr>
<tr>
<td class="style7">
选择文件:</td>
<td class="style3">
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
<td style="text-align: left">
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/WebControlUpload/shangchuan.JPG" onclick="ImageButton1_Click" />
</td>
</tr>
<tr>
<td colspan="3">
&nbsp;</td>
</tr>
</table>
</td>
</tr>
</table>

fileUpload.ascx.cs代码:

public partial class fileUpload : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
string serverPath = Server.MapPath("UpLoad"); //获取服务器端目录绝对路径
if (!System.IO.Directory.Exists(serverPath)) //如果不存在该目录
{
System.IO.Directory.CreateDirectory(serverPath); //创建该目录
}
if (FileUpload1.HasFile) //判断是否选择上传的文件
{
string imgtype = FileUpload1.PostedFile.ContentType;//获取客户端发送的文件类型
imgtype = imgtype.Substring(, );
if (imgtype != "image")
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('请选择图片');", true);
}
else
{
int filesize = FileUpload1.PostedFile.ContentLength / / ;//获取上传文件的大小
if (filesize > ) //如果大于8M
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('只允许上传不大于8兆的文件');", true); //弹出提示信息
return;
}
else //否则
{
//使用SaveAs方法将上传的文件存储到服务器中
FileUpload1.SaveAs(serverPath + "\\" + FileUpload1.FileName);
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('上传成功');", true);
}
}
}
else //如果没有选择文件
{
//弹出提示信息
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('请选择文件');", true);
return;
}
}
}

Default.aspx代码:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register src="fileUpload.ascx" tagname="fileUpload" tagprefix="uc1" %>
<!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>
<style type="text/css">
#form1
{
width: 639px;
height: 152px;
text-align: right;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<uc1:fileUpload ID="fileUpload1" runat="server" />
</form>
</body>
</html>

最终效果图:

037. asp.netWeb用户控件之五使用用户控件实现文件上传功能

上一篇:宏旺半导体深度剖析嵌入式存储芯片eMMC原理 一篇概括大全


下一篇:[转帖]深度剖析一站式分布式事务方案 Seata-Server