1.Form表單提交javascript
<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表單提交java
<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="提交" /> }
以上兩種方式,在後臺用同一種方法能夠獲取數據: 可是這兩種方法會形成頁面刷新,有時會影響用戶操做.ajax
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過去json
<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數據進行圖片預覽.post