您的位置:首页 > 编程语言 > ASP

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

2011-09-27 12:51 447 查看
第一步,新建文件upload.aspx

第二步,在upload.aspx的设计页面里放入<asp:FileUpload ID="ImgUpload" runat="server" />控件和button控件,button控件的单击代码如下.

第三步,写代码,代码如下:

if (ImgUpload.FileName != null)

{

string ImgName = ImgUpload.FileName;

string ImgExtention = System.IO.Path.GetExtension(ImgName);

int ImgSize = ImgUpload.PostedFile.ContentLength;//此处取得的文件大小的单位是byte

string ImgPath = Server.MapPath("~/upload_files/works/");//此处是你的项目下的文件夹

string ImgUrl = "upload_files/works/" + ImgName;//This is for the saving in the sql.

if (ImgExtention == ".gif" || ImgExtention == ".GIF" || ImgExtention == ".jpg" || ImgExtention == ".JPG" || ImgExtention == ".jpeg" || ImgExtention == ".JPEG")

{

if (ImgSize / 1024 < 1024)//转换为kb

{

ImgUpload.PostedFile.SaveAs(ImgPath + ImgName);

ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('上传图片成功!');</script>");

}

else

{

ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片大小不能超过1M!');</script>");

}

}

else

{

ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片格式不正确,只支持.gif/.jpg/.jpeg格式类型的图片!');</script>");

}

}

else

{

ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择要上传的图片!');</script>");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐