您的位置:首页 > 其它

MVC 通过ajaxSubmit上传图片并显示

2016-03-28 13:47 459 查看
js代码
function submitform() {
$("#form_upload").ajaxSubmit({
success: showResponse
});
}

function showResponse(responseText) {
if (responseText != null) {
alert('上传成功!');
} else {
alert('操作失败!');
}
}

$(function () {
$("#upImg").on("change", function () {
var file = this.files[0];

if (this.files && file) {
var reader = new FileReader();
reader.onload = function (e) {
$('#result').attr('src', e.target.result);
}
reader.readAsDataURL(file);
}
});
})
前台代码
<table>
<tr>
<td style="padding-top:20px;">生产(经营)许可证证件照片</td>
<td>
<form id="form_upload" style="height:4px;" action="Upload" target="iframeInfo" method="post" enctype="multipart/form-data">
<input name="upImg" id="upImg" type="file" />
<input type="submit" value="上传" />
</form>
</td>
</tr>
<tr>
<td>
<img id="result" style="width:200px;height:200px;" src="" alt="">
</td>
<td>
<iframe name="iframeInfo" id="iframeInfo" style="border:0px;"></iframe>
</td>
</tr>
</table>

(这里添加iframe,因为后台返回时会跳转,把form放入iframe里提交就不会跳转页面)
后台代码
[HttpPost]
public ActionResult Upload(HttpPostedFileBase upImg)
{
if (upImg == null)
{
return Content("文件上传错误,请重新选择文件!");

}
string fileName = System.IO.Path.GetFileName(upImg.FileName);
string filePhysicalPath = Server.MapPath("~/credimages/" + fileName);
try
{
upImg.SaveAs(filePhysicalPath);
Session["ImgPath"] = filePhysicalPath;
return Content("上传成功");
}
catch
{
return Content("上传异常 !");

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  MVC 上传图片