你的位置:首页 > Java教程

[Java教程]jQuery Ajax上传文件


JS代码:

//保存function btnAdd() {  var formData = new FormData($("#frm")[0]);  $.ajax({    url: "/Admin/ContentManage/SaveEdit",    type: "POST",    data: formData,    contentType: false, //必须false才会避开jQuery对 formdata 的默认处理     processData: false, //必须false才会自动加上正确的Content-Type    success: function (data) {      if (data == "OK") {        alert("保存成功");        $.iDialog("close"); //刷新父页面      }      else {        alert("保存失败:" + data);      }    }  });}

View Code

ASP.NET MVC后台代码:

//首先判断路径是否存在,不存在则创建路径string path = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["UploadsFiles"], folder + "/" + DateTime.Now.ToString("yyyyMMdd") + "/");string physicalPath = server.MapPath(path);if (!Directory.Exists(physicalPath)){  Directory.CreateDirectory(physicalPath);}HttpPostedFileBase file = request.Files[0];string newFileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);string savePath = Path.Combine(physicalPath, newFileName);file.SaveAs(savePath);fileName = file.FileName;string url = Path.Combine(path, newFileName);return url;

View Code