Javascript jQuery使用ajax发送文件到MVC控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33260463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:52:17  来源:igfitidea点击:

jQuery sending file with ajax to MVC Controller

javascriptjqueryajaxasp.net-mvc

提问by Sam

I'm trying to send a file using jQuery to my MVC controller but the action keeps receiving a null HttpPostedFileBase parameter.

我正在尝试使用 jQuery 将文件发送到我的 MVC 控制器,但该操作不断收到一个空的 HttpPostedFileBase 参数。

HTML:

HTML:

<input type="file" name="file" id="file" />
<input type="submit" name="submit" id="upload" value="Submit"/>

jQuery:

jQuery:

$(function () {
    $('#upload').click(function () {

        var data = new FormData($('#file')[0].files[0]);

        $.ajax({
            url: '@Url.Action("Upload", "Home")',
            type: 'POST',
            data: data,
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

Controller:

控制器:

[HttpPost]
public virtual ActionResult Upload(HttpPostedFileBase file)
{
    // file = null
}

new FormData($('#file')[0].files[0]):

new FormData($('#file')[0].files[0]):

__proto__: FormData

$('#file')[0].files[0]:

$('#file')[0].files[0]:

lastModified: 1445429215528
lastModifiedDate: Wed Oct 21 2015 14:06:55 GMT+0200 (Central Europe Daylight Time)
name: "Google_Chrome_logo_2011.jpg"
size: 5506
type: "image/jpg"
webkitRelativePath: ""
__proto__: File

I pretty much copied the code from other examples that I found on the internet but somehow it is just not working.

我几乎从互联网上找到的其他示例中复制了代码,但不知何故它只是不起作用。

回答by

Try this:

尝试这个:

if (Request.Files.Count > 0)
{
   foreach (string file in Request.Files)
   {
      var _file = Request.Files[file];
   }
}

UPDATE

更新

var $file = document.getElementById('file'),
    $formData = new FormData();

if ($file.files.length > 0) {
   for (var i = 0; i < $file.files.length; i++) {
      $formData.append('file-' + i, $file.files[i]);
   }
}

$.ajax({
   url: '/home/upload',
   type: 'POST',
   data: $formData,
   dataType: 'json',
   contentType: false,
   processData: false,
   success: function ($data) {

   }
 });