Asp. NET fileupload control is not supported by default for server-side onchange events, this can be accomplished in a flexible way.
This requires borrowing the client's onchange event, calling the __doPostBack method to simulate an event-triggering process with the LinkButton onclick event, as follows:
Client:
<asp:FileUpload ID=
"fuPhoto"
onchange=
"javascript:__doPostBack(‘lbUploadPhoto‘,‘‘)"
runat=
"server"
ToolTip=
"选择图片"
/>
<asp:LinkButton ID=
"lbUploadPhoto"
runat=
"server"
OnClick=
"lbUploadPhoto_Click"
></asp:LinkButton>
Background code:
//自动上传事件
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;
}
}
Asp. NET enables FileUpload controls to support the resolution of the automatic upload feature