ASP.NET的FileUpload控件默认是不支持服务端的onchange事件的,此时可以用一种变通的方法来实现这一功能。
这就需要借用客户端的onchange事件,调用__doPostBack方法来用LinkButton的OnClick事件模拟一个事件触发的过程,具体代码如下:
客户端:
1
2
|
<asp:FileUpload ID= "fuPhoto" onchange= "javascript:__doPostBack('lbUploadPhoto','')" runat= "server" ToolTip= "选择图片" />
<asp:LinkButton ID= "lbUploadPhoto" runat= "server" OnClick= "lbUploadPhoto_Click" ></asp:LinkButton>
|
后台代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
//自动上传事件
protected void lbUploadPhoto_Click( object sender, EventArgs e)
{
fileUpload();
}
//从控件上传文件
public void fileUpload()
{
if (fuPhoto.PostedFile != null && fuPhoto.PostedFile.ContentLength > 0)
{
string ext = System.IO.Path.GetExtension(fuPhoto.PostedFile.FileName).ToLower();
if (ext != ".jpg" && ext != ".jepg" && ext != ".bmp" && ext != ".gif" )
{
return ;
}
string filename = "Image_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) + ext;
string path = "./UploadPhoto/" + filename;
fuPhoto.PostedFile.SaveAs(Server.MapPath(path));
Response.Redirect( "ImageCut.aspx?Picurl=" + Server.UrlEncode(path));
}
else
{
//do some thing;
}
}
|