LayUI上传图片
前端:
//上传图片 layui.use('upload', function () { var upload = layui.upload; //普通图片上传 var uploadInst = upload.render({ elem: '#test1' , url: 'Upload' , before: function (obj) { //预读本地文件示例,不支持ie8 obj.preview(function (index, file, result) { $('#demo1').attr('src', result); //图片链接(base64) }); } , done: function (res) { //如果上传失败 if (res.code > 0) { return layer.msg('上传失败'); } //上传成功 $('#img').val(res.fileName); } , error: function () { //演示失败状态,并实现重传 var demoText = $('#demoText'); demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>'); demoText.find('.demo-reload').on('click', function () { uploadInst.upload(); }); } }); });
[HttpPost] public ActionResult Upload() { try { var file = Request.Files[0]; var filecombin = file.FileName.Split('.'); if (file == null || String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0 || filecombin.Length < 2) { return Json(new { fileid = 0, src = "", name = "", msg = "上传出错 请检查文件名 或 文件内容" }); } //定义本地路径位置 string local = "Upload\\" + System.DateTime.Now.ToString("yyyy-MM-dd"); string filePathName = string.Empty; string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, local); var tmpName = Server.MapPath("~/Upload/" + System.DateTime.Now.ToString("yyyy-MM-dd") + "/"); var tmp = file.FileName; var tmpIndex = 0; //判断是否存在相同文件名的文件 相同累加1继续判断 while (System.IO.File.Exists(tmpName + tmp)) { tmp = filecombin[0] + "_" + ++tmpIndex + "." + filecombin[1]; } //不带路径的最终文件名 filePathName = tmp; if (!System.IO.Directory.Exists(localPath)) System.IO.Directory.CreateDirectory(localPath); string localURL = Path.Combine(local, filePathName); file.SaveAs(Path.Combine(localPath, filePathName)); //保存图片(文件夹) return Json(new { src = localURL.Trim().Replace("\\", "/"), name = Path.GetFileNameWithoutExtension(file.FileName), // 获取文件名不含后缀名 msg = "上传成功", fileName = "~/Upload/" + System.DateTime.Now.ToString("yyyy-MM-dd") + "/" + filePathName//最终返回的路径及文件名称 }); } catch { } return Json(new { src = "", name = "", // 获取文件名不含后缀名 msg = "上传出错", fileName = "" }); }