javascript - 如何使用 jQuery 在 ASP.NET MVC 中上传文件?

标签 javascript jquery asp.net-mvc knockout.js form-data

我需要在 ASP.NET MVC 中上传文件。纯 javascript 代码可以工作(见下文),但是如果我将发送部分转换为 jQuery,则会出现 jquery 错误(第 8458 行)。

错误:

0x8000fff - JavaScript runtime error: Argument not optional
code: 
8453 jQuery.param = function( a, traditional ) {
8454    var prefix,
8455        s = [],
8456        add = function( key, value ) {
8457            // If value is a function, invoke it and return its value
8458            value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
8459            s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
8460        };

html:

<form data-bind='submit: upload'>
  <input type='file' id='fileInput' />
  <input type='submit' value='upload' />
</form>

js:

that.upload = function(){
  var data = new FormData();
  var fileInput = $('#fileInput')[0];
  var file = fileInput.files[0];
  data.append(file.name, file);
  var url = 'blah/Upload?id=' + that.id();

  // this pure js works
  var xhr = new XMLHttpRequest();
  xhr.open('post', url);
  xhr.send(data);

  // this jquery code does NOT work
  $.ajax({
      type: 'post',
      dataType: json',
      url: url,
      data: data,
  });
};

Controller :

public JsonResult Upload(string id){
  return Json(JsonConvert.SerializeObject(true), JsonRequestBehavior.DenyGet);
}

最佳答案

您需要添加 2 个额外的 ajax 选项,processData: falsecontentType: false

$.ajax({
  type: 'post',
  dataType: json',
  url: url,
  data: data,
  processData: false, // add
  contentType: false, // add
  ....
});

旁注:您应该使用 Url.Action() 来确保您的网址正确生成

var url = '@Url.Action("Upload", "blah")',

并将 id 值添加到 FormData

data.append(id, that.id);

关于javascript - 如何使用 jQuery 在 ASP.NET MVC 中上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32897882/

相关文章:

javascript - JSON.parse 返回 [Object object] 寻找访问对象的属性

javascript - 启动时打开 Karma debug.html 页面

javascript - SlickGrid 在分组级别显示聚合

c# - 使用 EPPlus 生成 excel 文件失败

asp.net-mvc - 在 ASP.Net MVC 中使用 System.Guid 作为主键?

c# - 在 Angular 6 和 ASP.net 中启用 CORS

javascript - 如何在 Javascript 中动态引用字符串?

javascript - Eclipse:创建新的 JavaScript 文件错误

jQuery animate() scrollTop 属性在 iPad Safari 上不起作用

jquery - if 语句运行失败