1.Form表单提交
<p>Form提交</p> <form action="@Url.Action("SavePictureByForm")" enctype="multipart/form-data" method="post"> <input id="pic" name="pic" type="file" /> <input type="submit" value="提交" /> </form>
2.Ajax.BeginForm,原理也是Form表单提交
<p>Ajax.BeginForm</p> @using(Ajax.BeginForm("SavePictureByForm", null, new AjaxOptions() { OnSuccess = "PostSuc", OnFailure = "PostFail", HttpMethod = "Post"}, new {enctype = "multipart/form-data"})) { <input type="file" name="pic" id="pic" multiple="multiple" /> <input type="submit" value="提交" /> }
以上两种方式,在后台用同一种方法可以获取数据: 但是这两种方法会造成页面刷新,有时会影响用户操作.
public ActionResult SavePictureByForm() { HttpFileCollectionBase files = Request.Files; var file = files[0]; bool isOk = false; string msg = string.Empty; //....OtherDO return Content("<script>window.location.href='/home/index';</script>"); }
3.Ajax提交 用此方法需要用到FileReader类,再获取到文件的Base64数据,将Base64数据Post过去
<p>Ajax:以上传图片为例</p> <input type="file" id="picAjax"/> <input type="button" id="submitPic" value="提交" /> <img id="selImg" src="" alt="用作图片预览" />
var picString = ""; $(function () { $("#picAjax").change(function (e) { var file = e.delegateTarget.files[0]; //在此可以对选择的文件进行判断:文件类型 文件大小等 //..... var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (ret) { picString = reader.result //预览图片 $("#selImg").attr({ "src": picString }); } }); $("#submitPic").click(function () { $.ajax("home/SavePicture", { type: "post", datatype: "json", data: picString, error: function () { }, success: function (result) { if (result) { alert(result.msg); } } }); });
后端接收
[HttpPost] public ActionResult SavePicture(string picString) { bool isOk = false; string msg = string.Empty; //其他操作 //......... //......... return Json(new { suc = isOk, msg = msg }); }
第三种方法做到了真正异步提交.但是如果选择的文件较大,可能会出现问题(未测试).
对于图片预览 前两种方法也可用base64数据进行图片预览.