繁体   English   中英

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

[英]How to upload file in ASP.NET MVC with jQuery?

我需要在ASP.NET MVC中上传文件。 纯JavaScript代码有效(请参见下文),但是如果我将send部分转换为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,
  });
};

控制器:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM