通过 JQuery AJAX 在 ASP.NET MVC 中上传文件

File Upload Through JQuery AJAX In ASP.NET MVC

我需要向候选人发送邀请,用户选择 excel 文件,将其从 ajax 传输到控制器并验证其大小、类型等。然后用户单击“发送邀请”按钮并发送电子邮件邀请(有 excel 文件)。请找到以下代码以供参考:

<button type="button" id="bulkuploadButton">Bulk Email Upload</button>
<input type="file" id="ExcelFile" name="ExcelFile" style="display:none" onchange="UploadFile();" onselect="UploadFile();" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />

Jquery:

function UploadFile() {
  if (ValidateExcelFile()) {
     var excelFile = document.getElementById('ExcelFile');
     formData = new FormData();
     if (excelFile.files.length > 0) {
        for (var i = 0; i < excelFile.files.length; i++) {
           formData.append('file-' + i, excelFile.files[i]);
        }
     }
     $.ajax({
       url: url here,
       type: "POST",
       dataType: 'json',
       processData: false,
       contentType: false,
       data: formData,
       success: function (data) {
        // Further Processing
       },
       error: function (err) {
        //Error
       }
     });
   }
}

控制器:

[HttpPost]
public JsonResult MyController(HttpPostedFileBase excelFile)
{
 if (Request.Files.Count > 0)
 {
   foreach (string file in Request.Files)
   {
     excelFile = Request.Files[file];
   }       
   var result = //Call Model here for validation checks and return error msges
   TempData["ExcelFile"] = excelFile; //Store in TempData for further processing
   return Json(result);
 }     
  return null;
}

验证已成功完成,现在是时候向候选人发送邀请了:

<button onclick="SendInvite">Send Invitations</button>

Jquery:

function SendInvite() {
  //Check validations for other inputs on the page

  //Get the excel file same as above
  var excelFile = document.getElementById('ExcelFile');
  formData = new FormData();
  if (excelFile.files.length > 0) {
    for (var i = 0; i < excelFile.files.length; i++) {
      formData.append('file-' + i, excelFile.files[i]);
    }
  }
  $.ajax({
    type: "POST",
    url: url here,
    data: JSON.stringify({
           myModel: myModel,
           excelFile: formData
          }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
    },
    error: function (data) {
    }
   });
}

控制器:

public JsonResult MyController2(MyModel myModel, HttpPostedFileBase excelFile)
{
 //I tried the same method to get the file but it didn't help me
 if (Request.Files.Count > 0)  //Here Request.Files.Count = 0, it should be = 1 instead
 {
  foreach (string file in Request.Files) 
  {
    excelFile = Request.Files[file];
  }
 }

 //I then tied to use TempData but it does not have the excel data

 excelFile = TempData["ExcelFile"] as HttpPostedFileBase;

 //Further processing

我在从 TempData 获取数据时遇到此错误。 ContentLength 为 0,数据属性也为 null

TempData 中的数据应该是这样的(其中 ContentLength !=0 并且数据属性有一些值):

谁能帮我获取控制器 MyController2 中的 excel 数据。

将函数 SendInvite() 更改为:

function SendInvite() {
  //Check validations for other inputs on the page

  //Get the excel file same as above
  var excelFile = document.getElementById('ExcelFile');
  formData = new FormData();

  formData.append("data", JSON.stringify(myModel));

  for (var i = 0; i < excelFile.files.length; i++) {
     var file = ExcelFile.files[i];
     formData.append("excelFile", file);
  }
  $.ajax({
    type: "POST",
    url: url here,
    data: formData,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    contentType: false,
    processData: false,
    success: function (data) {
    },
    error: function (data) {
    }
   });
}

并在控制器中

public JsonResult MyController2(string data, HttpPostedFileBase[] excelFile)
{
 MyModel myModel = JsonConvert.DeserializeObject<MyModel>(data);
 if (Request.Files.Count > 0)  
 {
  //Do data processing here
 }    

 //Further processing

勾选这个link