ajaxSubmit异步上传图片(嘘,外面都是假的)
电脑版发表于:2019/6/20 20:16
引用代码
<script src="/Scripts/jquery.form.js"></script>
js就在旁边img链接中,只不过大小为0x0,把jpg改为js即可使用
示例代码
前台:
$("#formscimg").ajaxSubmit({ url: "/CAUM/UploadImage", type: "Post", success: function (data) { if (data.msg.indexOf("成功") >= 0) { $("#addimgs").attr("src", data.src); $("#addimgsaa").val(data.src); } } });
后台:
public ActionResult UploadImage() { var item = Request.Files[0]; //UploadFiles/UploadImge string[] ssname = item.FileName.Split('.'); string path = "/UploadFiles/UploadImgs/" + Guid.NewGuid().ToString() + "-" + item.FileName; if (ssname.Length > 1) { string sstname = ssname.Last(); if (sstname == "jpg" || sstname == "png" || sstname == "gif" || sstname == "bmp" || sstname == "jpeg") { item.SaveAs(Server.MapPath(path)); return Json(new { src = path, name = Path.GetFileNameWithoutExtension(item.FileName), // 获取文件名不含后缀名 msg = "上传成功" }); } else { return Json(new { src = "", name = "", // 获取文件名不含后缀名 msg = "上传后缀有误!" }); } } return Json(new { src = "", name = "", // 获取文件名不含后缀名 msg = "上传出错" }); }
.net core中:
[HttpPost] public async Task<JsonResult> AddNews(AddNews news,IFormCollection collection) { if (news.NewsClassifyId<=0||string.IsNullOrEmpty(news.Title)||string.IsNullOrEmpty(news.Contents)) { return Json(new ResponseModel { code=0,result="参数有误" }); } var files = collection.Files; if (files.Count>0) { #region 判断图片大小 var change = _newsService.TheImglength(files[0].Length); if (change.code == 0)return Json(change); #endregion string webrootpath = _host.WebRootPath; string relavpath = "\\NewsPic"; string absolpath = webrootpath + relavpath; string[] fileTypes = new string[] { ".gif", ".jpg", ".jpeg", ".png", ".bmp" }; string extension = Path.GetExtension(files[0].FileName); if (fileTypes.Contains(extension)) { if (!Directory.Exists(absolpath)) { Directory.CreateDirectory(absolpath); } string fileName = DateTime.Now.ToString("yyyyMMddHHmmss")+extension; var filePath = absolpath + "\\" + fileName; using (var stream = new FileStream(filePath,FileMode.Create)) { await files[0].CopyToAsync(stream); } news.Image = "/NewsPic/" + fileName; return Json(_newsService.AddNews(news)); } return Json(new ResponseModel { code = 0, result = "图片格式有误" }); } return Json(new ResponseModel { code = 0, result = "请上传图片" }); }