MVC实现图片上传
首先,form表单的提交方法要声明为post,enctype属性声明为multipart/form-data。
后台方法:
//验证图片格式
public bool ValidateImg(string imgName)
{
string[] imgType = new string[] { "gif", "jpg", "png", "bmp" };
int i = 0;
bool ret = false;
string message = string.Empty;
//判断是否为Image类型文件
while (i < imgType.Length)
{
if (imgName.Equals(imgType[i].ToString()))
{
ret = true;
break;
}
else if (i == (imgType.Length - 1))
{
break;
}
else
{
i++;
}
}
return ret;
}
//上传图片
public string UploadImage()
{
string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string path = "/ItemImages/" + DateTime.Now.ToString("yyyyMMdd") + "/";
if (!System.IO.Directory.Exists(Server.MapPath(path)))
{
System.IO.Directory.CreateDirectory(Server.MapPath(path));
}
HttpPostedFileBase file = Request.Files[0];
if (file != null)
{
string strPath = file.FileName;
//获得上传图片的类型(后缀名)
string type = strPath.Substring(strPath.LastIndexOf(".") + 1).ToLower();
if (ValidateImg(type))
{
path += fileName + "." + type;
file.SaveAs(Server.MapPath(path));
return path;
}
else
{
return "";
}
}
return "";
}