后台獲取不到值方法一:
<script> layui.use('upload', function () { var upload = layui.upload; //執行實例 var uploadInst = upload.render({ elem: '#test1' //綁定元素 , url: '/Home/UploadFiles' //上傳接口 , field: "fileNames" //添加這個屬性與后台名稱保存一致 , accept: 'file' //允許上傳的文件類型 , size: 500000 //最大允許上傳的文件大小 , before: function (obj) { //obj參數包含的信息,跟 choose回調完全一致,可參見上文。 layer.load(); //上傳loading } , done: function (res) { //上傳完畢回調 alert(res.tc); } , error: function () { //請求異常回調 } }); }); </script>
public ActionResult UploadFiles(HttpPostedFileBase fileNames) { string path = ""; //小於20M if (fileNames.ContentLength > 0 && fileNames.ContentLength <= 120971520) { var fileName = Path.GetFileName(fileNames.FileName); string q_FN = fileName.Substring(0, fileName.LastIndexOf(".")); string h_FN = fileName.Substring(fileName.LastIndexOf(".")); string NewFileName = q_FN + DateTime.Now.ToString("yyyyMMddHHmmss") + h_FN; path = Path.Combine(Server.MapPath("/Uploadfile/"), NewFileName); fileNames.SaveAs(path); path = "/Uploadfile/" + NewFileName; var relt = new { tc = path }; return Content(JsonConvert.SerializeObject(relt)); } else { var relt = new { tc = "上傳文件要小於20M" }; return Content(JsonConvert.SerializeObject(relt)); } }
第二方式獲取 files
public ActionResult FileUpload() { HttpFileCollection uploadFiles = System.Web.HttpContext.Current.Request.Files; //上傳文件保存路徑 string savePath = Server.MapPath("/UploadFiles/"); try { for (int i = 0; i < uploadFiles.Count; i++) { //HttpPostedFile 對已上傳文件進行操作 //uploadFiles[i] 逐個獲取上傳文件 System.Web.HttpPostedFile postedFile = uploadFiles[i]; string fileName = System.IO.Path.GetFileName(postedFile.FileName); //獲取到名稱 string fileExtension = System.IO.Path.GetExtension(fileName);//文件的擴展名稱 string type = fileName.Substring(fileName.LastIndexOf(".") + 1); //類型 if (uploadFiles[i].ContentLength > 0) if (!System.IO.Directory.Exists(savePath)) { System.IO.Directory.CreateDirectory(savePath); } uploadFiles[i].SaveAs(savePath + fileName); } } catch (System.Exception Ex) { Response.Write(Ex); } return Content(""); }