前言:這里舉例是上傳文件、上傳圖片同理!
注意:layui.js版本必須使用2.0版本以上,否則線上會出現上傳跨域(CORS)問題!
一、 layu0 JSi聲明、調用
layui.use('upload',function() { var upload=layui.upload; //執行實例 var uploadInst = upload.render({ elem: '#test1' //綁定元素 ,url: '/upload/' //上傳接口 , accept: 'file'//允許上傳的文件類型 , multiple: true , auto: true ,done: function(res){ //上傳完畢回調 } ,error: function(){ //請求異常回調 } }); })
二、WebAPI接收上傳的文件信息,並處理
public IHttpActionResult Get() { if (HttpContext.Current.Request.Files.Count > 0) { try { string filePath = "~/File/demo/"; //得到客戶端上傳的文件 HttpPostedFile file = HttpContext.Current.Request.Files[0]; //如果文件不存在就重新創建一個 if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(filePath))) { Directory.CreateDirectory(HttpContext.Current.Server.MapPath(filePath)); } //服務器端要保存的路徑 filePath = HttpContext.Current.Server.MapPath(filePath) + file.FileName;// +".txt"; file.SaveAs(filePath); //返回結果 return Json(new { res = "success", filePath = "~/File/demo/" + file.FileName }); } catch (Exception ex) { return Json(new { res = ex.Message }); } } else { return Json(new { res = "error" }); ; //Response.Write("Error1"); } }