.net上传图片格式和大小约束
前台代码:
<form id="form1" runat="server">
<br />
<input id="fileUpLoad" type="file" runat="server" /> 大小为:130*140<br />
<asp:Button ID="Button1" runat="server" Text="上传" onclick="Button1_Click1"
style="height: 26px" />
</form>
后台代码:
protected void Button1_Click1(object sender, EventArgs e)
{
//获取文件在客户端计算机上的完全路径名(例如"D:/myfiles/lo.txt")
string fullFileName=this.fileUpLoad.PostedFile.FileName;
//获取文件的具体文件名(例如"lo.txt")
string fileName=fullFileName.Substring(fullFileName.LastIndexOf(@"/")+1);
//获取文件的扩展名(例如"txt")
string typeName=(fullFileName.Substring(fullFileName.LastIndexOf(".")+1)).ToLower();
//判断上传文件的格式是否是图片格式
//如是是就上传
if (typeName == "jpg" || typeName == "bmp" || typeName == "gif" || typeName == "jpeg")
{
if (ValidateFileDimensions())
{
this.fileUpLoad.PostedFile.SaveAs(Server.MapPath("~/ProductImages/") + fileName);//+ @"/"
Response.Write("上传成功");
}
else
{
Response.Write("图片大小不符合要求");
}
}
else
{
Response.Write("<script languge='javascript'>alert('你的图片格式错误!');</script>");
}
}
//判断图片的大小
public bool ValidateFileDimensions()
{
using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fileUpLoad.PostedFile.InputStream))
{
return (myImage.Height == height && myImage.Width == width);
}
}