前言:
多图上传在一些特殊的需求中我们经常会遇到,其实多图上传的原理大家都有各自的见解。对于Layui多图上传和我之前所说的通过js获取文本框中的文件数组遍历提交的原理一样,只不过是Layui中的upload.render方法已经帮我们封装好了,我们只管调用即可,也就是说你选中了几张图片,那么将会向后台请求与图片张数相同的次数,即为遍历提交的方式。
Layui文件/图片样式地址(官方文档):https://www.layui.com/demo/upload.html
一、引入Layui.css和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
二、前端代码:
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>
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>
三、服务端接口图片文件流,并保存:
public class FileUploadController : Controller { /// <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; } }