MVC upload image MVC上传图片的例子
直接上MVC上传图片的代码了。
View :
代码
<% using (Html.BeginForm(Html.ViewContext.RouteData.Values["action"].ToString(), Html.ViewContext.RouteData.Values["controller"].ToString(), FormMethod.Post, new { enctype = "multipart/form-data" }))
{ %>
<div>
<table>
<tr>
<td>
文章图片
</td>
<td>
<input id="txtUploadFile" type="file" name="file" accept="image/gif" onchange="return FilterFileType();" style="width:350px;" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" onclick="$('#IsPublish').attr('value','True');" value="保存并发布" />
</td>
</tr>
</table>
</div>
<script type="text/javascript">
function FilterFileType() {
var fullName = document.getElementById("txtUploadFile").value;
if (fullName != "")
{
var s,ss;
var s = fullName;
ss= s.substr(s.length-4,s.length);
if (ss!=".gif" && ss!=".jpg" && ss!=".bmp")
{
alert("图片文件上传只支持.gif .jpg .bmp");
return (false);
}
}
}
</script>
<% } %>
{ %>
<div>
<table>
<tr>
<td>
文章图片
</td>
<td>
<input id="txtUploadFile" type="file" name="file" accept="image/gif" onchange="return FilterFileType();" style="width:350px;" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" onclick="$('#IsPublish').attr('value','True');" value="保存并发布" />
</td>
</tr>
</table>
</div>
<script type="text/javascript">
function FilterFileType() {
var fullName = document.getElementById("txtUploadFile").value;
if (fullName != "")
{
var s,ss;
var s = fullName;
ss= s.substr(s.length-4,s.length);
if (ss!=".gif" && ss!=".jpg" && ss!=".bmp")
{
alert("图片文件上传只支持.gif .jpg .bmp");
return (false);
}
}
}
</script>
<% } %>
Controller:
代码
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult Create(HttpPostedFileBase file)
{
try
{
if (file != null)
{
var fileName = Path.Combine(Request.MapPath("~/App_Data/Image"), Path.GetFileName(file.FileName));
file.SaveAs(fileName);//保存Img图片
}
}
catch(Exception e)
{
}
return View();
// If we got this far, something failed, redisplay form
}
[ValidateInput(false)]
public ActionResult Create(HttpPostedFileBase file)
{
try
{
if (file != null)
{
var fileName = Path.Combine(Request.MapPath("~/App_Data/Image"), Path.GetFileName(file.FileName));
file.SaveAs(fileName);//保存Img图片
}
}
catch(Exception e)
{
}
return View();
// If we got this far, something failed, redisplay form
}