簡體   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