MVC非同步上傳圖片
阿新 • • 發佈:2019-01-23
今天聽黑馬訓練營就業班的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>