view:
<body> <form id="form1" method="post" action="@Url.Action("UploadFile","Mydemo")" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit" value="提交" /> </form> </body>
Controller:
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
return Content("");
}
用普通的ajax提交表单的时候,不能把文件流传到后端去,所以要用到jquery.form.js
jquery.form.js到官网下载或者从这里下载:http://pan.baidu.com/s/1c2JS60C
view:
<script src="~/Scripts/jquery-1.7.1.min.js"></script> <script src="~/Scripts/jquery.form.js"></script> </head> <body> <form id="form1"> <input type="file" name="file"/> <input type="button" value="提交" onclick="sub()" /> </form> </body> </html> <script type="text/javascript"> function sub() { $("#form1").ajaxSubmit({ url: "@Url.Action("UploadFile", "Mydemo")", type: "post", success: function (data) { //...... }, error: function (aa) { alert(aa); } }); } </script>
Controller:
[HttpPost] public ActionResult UploadFile(HttpPostedFileBase file) { return Content(""); }