简体   繁体   English

jQuery使用Ajax将文件发送到MVC控制器

[英]jQuery sending file with ajax to MVC Controller

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]): 新的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. 我几乎复制了我在互联网上找到的其他示例中的代码,但以某种方式无法正常工作。

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

   }
 });

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

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