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

第一步,新建文件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>");
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值