首页 > 解决方案 > 在 ASP.NET MVC 中通过 JQuery AJAX 上传文件

问题描述

我需要向候选人发送邀请,其中用户选择 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" />

查询:

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>

查询:

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 且数据属性为空 错误

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

临时数据

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

标签: c#jqueryajaxfile-uploadhttppostedfilebase

解决方案


将函数 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

检查此链接如何将图像文件和表单数据从 Ajax 传递到 MVC 控制器


推荐阅读