标签:style blog http color io os java ar strong
FileUpload控件实现单按钮图片自动上传并带预览显示
1 <asp:FileUpload ID="fuPhoto" onchange="javascript:__doPostBack(‘lbtnUpload‘,‘‘)" runat="server" ToolTip="选择图片" ForeColor="White" Width="68"/> 2 <asp:LinkButton ID="lbtnUpload" runat="server" OnClick="lbUploadPhoto_Click"></asp:LinkButton> 3 <img id="img" runat="server" src="" />
后台代码:
1 /// <summary> 2 /// 自动上传事件 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 protected void lbUploadPhoto_Click(object sender, EventArgs e) 7 { 8 fileUpload(); 9 } 10 //从控件上传文件 11 public void fileUpload() 12 { 13 if (fuPhoto.PostedFile != null && fuPhoto.PostedFile.ContentLength > 0) 14 { 15 //1. 验证文件格式 16 string ext = System.IO.Path.GetExtension(fuPhoto.PostedFile.FileName).ToLower(); 17 if (ext != ".jpg" && ext != ".gif"&&ext!=".png") 18 { 19 Response.Write("文件非法!"); 20 return; 21 } 22 string savePath = Server.MapPath("~/upload/");//指定上传文件在服务器上的保存路径 23 //2. 检查服务器上是否存在这个物理路径,如果不存在则创建 24 if (!System.IO.Directory.Exists(savePath)) 25 { 26 System.IO.Directory.CreateDirectory(savePath); 27 } 28 Random random = new Random(DateTime.Now.Millisecond); 29 string fileName = DateTime.Now.ToString("yyMMddhhmmss") + random.Next(10000)+ext; 30 string path = savePath + fileName; 31 fuPhoto.PostedFile.SaveAs(path); 32 this.img1.Src = "upload/" + fileName; 33 } 34 else 35 { 36 //do some thing; 37 } 38 }
标签:style blog http color io os java ar strong
原文地址:http://www.cnblogs.com/xyyt/p/3978562.html