Layui上传图片2.0版
1.View
<button type="button" class="layui-btn" id="test"></button> <h3>预览</h3> <img id ="img" src="">
2.Js
<script> $(function () { layui.use('upload', initUp); }) function initUp() { var upload = layui.upload; //执行实例 var uploadInst = upload.render({ elem: '#test', //绑定元素 url: '/Home/SaveImages', //上传接口 accept: "images", //默认是图片类型 images exts: "", //扩展名的限制 done: function (res) { //上传完毕回调 if (res.code == 0) { var url = "/Home/GetImage?imgName=" + res.data + "&_dc=new Date()"; $("#img").attr("src", url); } }, error: function () { //请求异常回调 }, }); } </script>
3.Controller
string IMAGES_PATH = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"App_Data\images"); //定义存放图片文件夹 public JsonResult SaveImages() { LayUIVOState vo = new LayUIVOState(); var files = HttpContext.Request.Files; if (files.Count == 0) { vo.code = -1; } else { HttpPostedFileBase file = files[0]; string fileName = file.FileName; string fullName = Path.Combine(IMAGES_PATH, fileName); file.SaveAs(fullName); vo.data = fileName; } return Json(vo); } public FileResult GetImage(string imgName) { string path = Path.Combine(IMAGES_PATH, imgName); return new FileStreamResult(new FileStream(path, FileMode.Open), "image/jpeg"); }
4.Models
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace UploadFiles.Models { public class LayUIVOState { public int code { get; set; } public string msg { get; set; } public object data { get; set; } } }