asp.net(C#)上传单个图片并判断图片的类型和大小

 1 第一步,新建文件upload.aspx
2 第二步,在upload.aspx的设计页面里放入<asp:FileUpload ID="ImgUpload" runat="server" />控件和button控件,button控件的单击代码如下.
3 第三步,写代码,代码如下:
4 if (ImgUpload.FileName != null)
5 {
6 string ImgName = ImgUpload.FileName;
7 string ImgExtention = System.IO.Path.GetExtension(ImgName);
8 int ImgSize = ImgUpload.PostedFile.ContentLength;//此处取得的文件大小的单位是byte
9 string ImgPath = Server.MapPath("~/upload_files/works/");//此处是你的项目下的文件夹
10 string ImgUrl = "upload_files/works/" + ImgName;//This is for the saving in the sql.
11 if (ImgExtention == ".gif" || ImgExtention == ".GIF" || ImgExtention == ".jpg" || ImgExtention == ".JPG" || ImgExtention == ".jpeg" || ImgExtention == ".JPEG")
12 {
13 if (ImgSize / 1024 < 1024)//转换为kb
14 {
15 ImgUpload.PostedFile.SaveAs(ImgPath + ImgName);
16 ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('上传图片成功!');</script>");
17 }
18 else
19 {
20 ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片大小不能超过1M!');</script>");
21 }
22 }
23 else
24 {
25 ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片格式不正确,只支持.gif/.jpg/.jpeg格式类型的图片!');</script>");
26 }
27 }
28 else
29 {
30 ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择要上传的图片!');</script>");
31 }

 

posted @ 2012-02-22 16:40  SOD_QWER  阅读(696)  评论(1)    收藏  举报