Asp.Net MVC Ajax
在asp.net MVC 使用Ajax时 实现图片上传时总是获取不到要上传的文件
视图如下:
<%using (Ajax.BeginForm("AjaxCreatStationPhoto", new AjaxOptions { UpdateTargetId = "View", LoadingElementId = "Loding" }))
{ %>
<table style="width: 100%;">
<tr>
<td style="width: 50%; vertical-align: top;">
<table width="100%" border="0" cellpadding="0" cellspacing="1" style="background-color: #a8bdce;">
<tr class="trAll">
<td class="tdTitle">
<span class="spanTitle">站点图片:</span>
</td>
<td class="tdContent" style="text-align: center;">
<img alt="" src="" id="img1" style="height:50px; width:50px;"/><br />
<input id="File1" type="file" name="File1" onchange="return fileshow()"/>
</td>
</tr>
<tr class="trAll">
<td class="tdTitle" colspan="2">
<input id="AddPhoto" type="submit" value="" name="AddPhoto" style="width: 70px; height: 23px;
background: url(/Content/images/baocuntuichu.gif) no-repeat 50% 0; border: none;
float: left;" />
<input id="AddPhotoNext" type="submit" value="" name="AddPhotoNext" style="width: 70px;
height: 23px; background: url(/Content/images/jixutianjia.gif) no-repeat 50% 0;
border: none; float: right;" />
</td>
</tr>
</table>
<%}%>
控制器:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AjaxCreatStationPhoto(string id, FormCollection collection, HttpPostedFileBase File1)
{
string str = string.Empty;
tb_Global_Photo photo = new tb_Global_Photo();
photo.photoID = Guid.NewGuid().ToString();
HttpPostedFileBase file = Request.Files[0];
string path = Server.MapPath("~/images/stationImage/");
if (file != null)
{
//获取用户上传的文件类型
string fileExtension = System.IO.Path.GetExtension(file.FileName).ToLower();
//设置限定的文件类型
string[] allowedExtension = { ".jpg", ".jpeg", ".gif", ".bmp", ".png" };
bool Exist = false;
//判断用户上传的文件类型是否受限,如果受限则不允许上传
for (int i = 0; i < allowedExtension.Length; i++)
{
if (fileExtension == allowedExtension[i])
{
Exist = true;
}
}
if (!Exist)
{
return RedirectToAction("PhotoFormat");
}
string[] filesplit = file.FileName.Split('\\');
string filename=filesplit[filesplit.Length-1];
file.SaveAs(path + filename);
photo.photoURL = filename;
}