今天听黑马训练营就业班的MVC课程,马老师在异步上传图片这里卡住了半天,多次调试都无法在后台控制器获得图片。
下面直接写出MVC中文件上传方法。
1.控制器
public ActionResult ImageUpload()
{
return View();
}
public ActionResult ProcessImgUpload()
{
var file=Request.Files["imgFile"];
string path="/Upload/"+Guid.NewGuid().ToString()+file.FileName;
string savepath = Request.MapPath(path);
file.SaveAs(savepath);
return Content(path);
}
2.View视图
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>ImageUpload</title>
<script src="../../Script/jquery-1.7.1.js"></script>
<script src="../../Script/MyAjaxForm.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSub").click(function () {
$("#frm").ajaxSubmit({
url: "/Ajax/ProcessImgUpload",
type: "Post",
success: afterUpload
});
return false;
});
});
function afterUpload(data) {
$("#result").html("<img src='" + data + "'/>");
}
</script>
</head>
<body>
<div>
<form action="/ajax/ProcessImgUpload" data-ajax="true" data-ajax-method="Post" data-ajax-success="afterUpload" enctype="multipart/form-data" id="frm" method="post">
<input type="file" name="imgFile" id="imgFile" />
<input type="submit" id="btnSub" value="异步上传图片" />
</form>
<div id="result"></div>
</div>
</body>
</html>
测试成功,能够实现图片的异步上传。