基于jQuery Ajax實(shí)現(xiàn)上傳文件

字號(hào):


    本文實(shí)例為大家分享了基于jQuery Ajax實(shí)現(xiàn)上傳文件的關(guān)鍵代碼,供大家參考,具體內(nèi)容如下
    JS代碼:
    //保存
    function btnAdd() {
      var formData = new FormData($("#frm")[0]);
      $.ajax({
        url: "/Admin/ContentManage/SaveEdit",
        type: "POST",
        data: formData,
        contentType: false, //必須false才會(huì)避開jQuery對(duì) formdata 的默認(rèn)處理 XMLHttpRequest會(huì)對(duì) formdata 進(jìn)行正確的處理  
        processData: false, //必須false才會(huì)自動(dòng)加上正確的Content-Type
        success: function (data) {
          if (data == "OK") {
            alert("保存成功");
            $.iDialog("close"); //刷新父頁(yè)面
          }
          else {
            alert("保存失?。? + data);
          }
        }
      });
    }
    ASP.NET MVC后臺(tái)代碼:
    //首先判斷路徑是否存在,不存在則創(chuàng)建路徑
    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;
    以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。