Asp.net 上传文件小叙(修改FileUpload显示文字等)

想要在asp.net网站上上传文件就得用到FileUpload,可是这个控件中“浏览”没法修改,可以使用html中<input type="file" 来解决该问题。

首先页面不能使用updatepannel,然后需要在页面form中添加method="post" enctype="multipart/form-data" 

例如

 <form id="form1" runat="server"  method="post" enctype="multipart/form-data">

然后在页面需要的位置放此代码

<input type="text" id="txtPath" name="txt"  style="width:250px"  runat="server" /> 
<input type="button" onmousemove="f.style.pixelLeft=event.x-60;f.style.pixelTop=this.offsetTop;" value="Select" size="30" onclick="f.click()" /> 
<input type="file" id="f" runat="server" onchange="txtPath.value=this.value" accept="image/gif, image/jpeg" name="f" style="position:absolute;filter:alpha(opacity=0);" size="1" hidefocus="true" />

然后在上传按钮事件中这样写

 1 // 获取客户端上载文件
 2 HttpPostedFile UserHPF = Request.Files["f"];
 3 //获取文件夹路径
 4 string FilePath = Server.MapPath("./");
 5 string newfilepath = FilePath + "\\" + System.IO.Path.GetFileName(UserHPF.FileName);
 6 //将上传的文件存储在指定目录下
 7 UserHPF.SaveAs(newfilepath);
 8 
 9 if (File.Exists(newfilepath))
10 {
11       WebMessageBox(this,"Import license file successfully!");
12 }

通过这个方法HttpPostedFile UserHPF = Request.Files["f"];就能取到要上传的文件了 然后就是常规的SaveAs了。

 

posted @ 2016-03-09 13:08  zlsyl  阅读(1218)  评论(0编辑  收藏  举报