標籤:ppa file highlight control har pre saveas uri 頭像
1、下載ajaxfileupload.js
2、在控制器內建立如下方法
//檔案上傳 public ActionResult uploadFile(HttpPostedFileBase file) { if (file == null) { return Json(new { result = "false", errorMsg="檔案不存在" }, "text/html"); } string fileName = "~/UploadFiles/" + DateTime.Now.ToString("yyyyMMddHHssmm") + Path.GetFileName(file.FileName); var physicsFileName = Server.MapPath(fileName); try { file.SaveAs(physicsFileName); return Json(new { result = "true", imgUrl = fileName }, "text/html"); } catch(Exception ex) { return Json(new { result = "false", errorMsg = ex.Message }, "text/html"); } }
3、在前端編寫如下JS,需要引入JQuery和ajaxfileupload.js
<script type="text/javascript"> function ajaxFileUploads() { $("#loading").ajaxStart(function () { $(this).show(); }).ajaxComplete(function () { $(this).hide(); }); $.ajaxFileUpload({ url: ‘/User/uploadFile‘, //幕後處理的 - Controller/Action secureuri: false, fileElementId: ‘fileToUpload‘, //上傳檔案的Name屬性 dataType: ‘json‘, type: ‘post‘, success: function (data, status) { alert(data.result); if (data.result === "true") { //成功後把後台檔案路徑賦值給異常控制項,便於一起提交給後台 alert(data.imgUrl); $(".imgUrl").val(data.imgUrl); } else if (data.result === "false") { alert(data.errorMsg); } }, error: function (data, status, e) { alert(e); } }) return false; } $(document).ready(function () { $(".btnUpload").click(function () { ajaxFileUploads(); }); }); </script>
4、View中的代碼
<div> 個人頭像:@Html.HiddenFor(m => m.imgUrl, new { @class = "imgUrl" }) //強型別綁定 <input type="file" id="fileToUpload" name="file" /><input type="button" class="btnUpload" value="上傳" /> //上傳控制項和上傳按鈕 <span id="loading" style="display: none;">請等待</span> //等待提示 </div>
asp.net MVC4 非同步檔案上傳