layui upload 后台获取不到值
后台获取不到值方法一:
<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(""); }