前言:
多圖上傳在一些特殊的需求中我們經常會遇到,其實多圖上傳的原理大家都有各自的見解。對於Layui多圖上傳和我之前所說的通過js獲取文字框中的檔案陣列遍歷提交的原理一樣,只不過是Layui中的upload.render方法已經幫我們封裝好了,我們只管呼叫即可,也就是說你選中了幾張圖片,那麼將會向後臺請求與圖片張數相同的次數,即為遍歷提交的方式。
Layui檔案/圖片樣式地址(官方文件):https://www.layui.com/demo/upload.html
一、引入Layui.cs和Layui.js:
需要本地專案中存在layui相關樣式和js,非網路地址
<link rel="stylesheet" href="//res.layui.com/layui/dist/css/layui.css" media="all">
<script src="//res.layui.com/layui/dist/layui.js" charset="utf-8"></script>
當然假如你需要有彈框提示的話,你還需要引入Layer.js
二、前端程式碼:
a.Html中的程式碼:
<li> <h6>滾動圖片:</h6> <div class="layui-upload"> <button type="button" class="layui-btn" id="test2">滾動圖片上傳【推薦上傳三張】</button> <button type="button" class="layui-btn layui-btn-danger" onclick="clearAll()"><i class="layui-icon"></i></button> <input type="hidden" name="ScrollingGraph" id="ScrollingGraph"/> <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;"> 預覽圖: <div class="layui-upload-list" id="demo2"></div> </blockquote> </div> </li>
b.js中的程式碼:
<script> layui.use('upload', function () { var $ = layui.jquery, upload = layui.upload; //多圖片上傳 upload.render({ elem: '#test2', url: '/FileUpload/FileLoad/', multiple: true,//允許選擇多張圖片 before: function (obj) { //預讀本地檔案示例,不支援ie8 obj.preview(function (index, file, result) { $('#demo2').append( '<img src="' + result + '" alt="' + file.name + '" class="layui-upload-img">'); }); }, done: function (res) { if (res.isSuccess == true) { layer.msg("上傳成功"); var scrollingGraph = $("#ScrollingGraph").val(); if (scrollingGraph == "") { $("#ScrollingGraph").val(res.path); } else { scrollingGraph += ',' + res.path; $("#ScrollingGraph").val(scrollingGraph); } console.log(scrollingGraph); } else { return layer.msg('上傳失敗'); } } }); }); //清空所有圖片 function clearAll() { layer.confirm("確定要全部清空嗎?", { icon: 3, btn: ["確定", "取消"], yes: function (index) { $("#demo2").html(""); $("#ScrollingGraph").val(""); layer.close(index); } }); } </script>
三、服務端介面圖片檔案流,並儲存:
1public class FileUploadController : Controller 2{ 3/// <summary> /// 對驗證和處理 HTML 窗體中的輸入資料所需的資訊進行封裝,如FromData拼接而成的檔案 /// </summary> /// <param name="context">FemContext對驗證和處理html窗體中輸入的資料進行封裝</param> /// <returns></returns> [HttpPost] public ActionResult FileLoad(FormContext context) { HttpPostedFileBase httpPostedFileBase = Request.Files[0];//獲取二進位制圖片檔案流 if (httpPostedFileBase != null) { try { ControllerContext.HttpContext.Request.ContentEncoding = Encoding.GetEncoding("UTF-8"); ControllerContext.HttpContext.Response.Charset = "UTF-8"; string fileName = Path.GetFileName(httpPostedFileBase.FileName);//原始檔名稱 string fileExtension = Path.GetExtension(fileName);//副檔名 byte[] fileData = ReadFileBytes(httpPostedFileBase);//檔案流轉化為二進位制位元組 string result = SaveFile(fileExtension, fileData);//檔案儲存 if (string.IsNullOrEmpty(result)) { return Json(new { isSuccess = false, path = "",errorMsg= "上傳檔案失敗"}); } return Json(new { isSuccess = true, path = result }); } catch (Exception ex) { return Json(new { isSuccess = false, path = "" }); } } else { return Json(new { isSuccess = false, path = "" }); } } /// <summary> /// 將檔案流轉化為二進位制位元組 /// </summary> /// <param name="fileData">圖片檔案流</param> /// <returns></returns> private byte[] ReadFileBytes(HttpPostedFileBase fileData) { byte[] data; using (Stream inputStream = fileData.InputStream) { MemoryStream memoryStream = inputStream as MemoryStream; if (memoryStream == null) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } data = memoryStream.ToArray(); } return data; } /// <summary> /// 儲存檔案 /// </summary> /// <param name="fileExtension">副檔名</param> /// <param name="fileData">圖片二進位制檔案資訊</param> /// <returns></returns> private string SaveFile(string fileExtension, byte[] fileData) { string result; try { string saveName = Guid.NewGuid().ToString()+ fileExtension; //儲存檔名稱 // 檔案上傳後的儲存路徑 string basePath = "UploadFile"; string saveDir = DateTime.Now.ToString("yyyy-MM-dd"); string savePath = System.IO.Path.Combine(saveDir, saveName); string serverDir = System.IO.Path.Combine(Server.MapPath("~/"), basePath, saveDir); if (!System.IO.Directory.Exists(serverDir)) { System.IO.Directory.CreateDirectory(serverDir); } string fileNme = System.IO.Path.Combine(serverDir, saveName);//儲存檔案完整路徑 System.IO.File.WriteAllBytes(fileNme, fileData);//WriteAllBytes建立一個新的檔案,按照對應的檔案流寫入,假如已存在則覆蓋 //返回完整的圖片儲存地址 result="/"+basePath + "/" + saveDir + "/" + saveName; } catch (Exception) { result = "發生錯誤"; } return result; } }