视图
@using (Html.BeginForm("HeroAdd", "Hero", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td>头像:</td>
<td><input type="file" name="Hicon" id='File1' /></td>
</tr>
<tr>
<td>名称:</td>
<td>@Html.TextBoxFor(a => a.HName)</td>
</tr>
<tr>
<td>阵营:</td>
<td>@Html.DropDownList("CampID")</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="添加" onclick='fileclick()'/></td>
</tr>
</table>
}
必须添加new { enctype = "multipart/form-data" }
后台代码 HttpPostedFileBase 接收图片
public ActionResult HeroAdd(Hero Add, HttpPostedFileBase Hicon)
{
if (Hicon != null)
{
string imgName = DateTime.Now.ToString("yyyymmddss") + Hicon.FileName.Substring(Hicon.FileName.LastIndexOf('.'));//根据日期修改图片名称
Hicon.SaveAs(Server.MapPath("/image/" + imgName));//将图片上传到image文件夹中
Add.Hicon = "/image/" + imgName; //存储数据库路径
}
}
//使用js判断图片类型
function fileclick(){
var f=document.getElementById("File1").value;
if(f=="")
{ alert("请上传图片");return false;}
else
{
if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(f))
{
alert("图片类型必须是.gif,jpeg,jpg,png中的一种")
return false;
}
}
}
@using (Html.BeginForm("HeroAdd", "Hero", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td>头像:</td>
<td><input type="file" name="Hicon" id='File1' /></td>
</tr>
<tr>
<td>名称:</td>
<td>@Html.TextBoxFor(a => a.HName)</td>
</tr>
<tr>
<td>阵营:</td>
<td>@Html.DropDownList("CampID")</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="添加" onclick='fileclick()'/></td>
</tr>
</table>
}
必须添加new { enctype = "multipart/form-data" }
后台代码 HttpPostedFileBase 接收图片
public ActionResult HeroAdd(Hero Add, HttpPostedFileBase Hicon)
{
if (Hicon != null)
{
string imgName = DateTime.Now.ToString("yyyymmddss") + Hicon.FileName.Substring(Hicon.FileName.LastIndexOf('.'));//根据日期修改图片名称
Hicon.SaveAs(Server.MapPath("/image/" + imgName));//将图片上传到image文件夹中
Add.Hicon = "/image/" + imgName; //存储数据库路径
}
}
//使用js判断图片类型
function fileclick(){
var f=document.getElementById("File1").value;
if(f=="")
{ alert("请上传图片");return false;}
else
{
if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(f))
{
alert("图片类型必须是.gif,jpeg,jpg,png中的一种")
return false;
}
}
}