简体   繁体   中英

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

I need to upload files in ASP.NET MVC. the pure javascript code works (see below), but if I convert the send part to jQuery, it gives me a jquery error (line 8458).

error:

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

You need to add 2 additional ajax options, processData: false and contentType: false

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

Side note: You should use Url.Action() to ensure your url is correctly generated

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

and add the id value to FormData

data.append(id, that.id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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