上传文件时Ajax调用没有命中动作方法

时间:2017-06-20 04:32:56

标签: jquery asp.net-mvc-4

我正在使用MVC应用程序,我使用了一个拖放文件上传,工作正常,文件正在相应的文件夹中上传。

以下是用于它的示例代码:

<div id="dropZone" style="width:340px; height:200px">
    <b> Drop your files here or</b> 
</div>
<img id="uploadImg" src="~/Content/images/Cloud-File.gif" alt="uploadFile" style="width:297px; height:155px; display:none" />


$('#dropZone').filedrop({
    url: '@Url.Action("UploadFiles","Home")',
    paramname: 'files',
    maxFiles: 5,
    dragOver: function () {
       //change color
    },
    dragLeave: function () {
      //change color
    },
    drop: function () {
       //change color
    },
    afterAll: function () {

    },
    uploadFinished: function (i, file, response, time)
    {
      //creating file size and showing the file name in list
    }
});

以下是用于它的控制器。

[HttpPost]
public ActionResult UploadFiles(IEnumerable files)
{
    foreach (HttpPostedFileBase file in files)
    {
      //save logic
    }
    return Json("All files have been successfully stored.");
}

直到这里一切都很好没有问题之后我也为手动上传文件添加了一个输入文件控件。 下面是用于它的jquery ajax调用:

$("#upload").change(function () {
    var fileInfo = $("#upload").prop('files');
    var fileData = new FormData();
    fileData.append('files',fileInfo[0])
    $.ajax({
        type: "POST",
        url: '@Url.Action("UploadFiles", "Home")',
        processData:false,
        // contentType: "application/json; charset=utf-8",
        // data: { files: fileData},
        dataType: "json",
        async:false,
        success: function (response) { UploadBrowseFile(fileInfo[0]); },
        error: function (xhr, status, error) { alert(xhr.responseText); }
    });
});

但它没有达到相同的控制器操作,而且进程正在转向错误功能,由于此手动上传无效。 需要帮助。

1 个答案:

答案 0 :(得分:2)

您当前未向该方法发送任何数据(data选项的注释代码不正确),并且您发送contentType的{​​{1}}选项不正确,且必须是设置为FormData(默认为false)。

将ajax选项更改为

'application/x-www-form-urlencoded; charset=UTF-8'

您还需要将方法的签名更改为

$.ajax({
    type: "POST",
    url: '@Url.Action("UploadFiles", "Home")',
    processData:false,
    contentType: false, // change
    data: fileData, // change
    dataType: "json",
    async:false,
    success: function (response) { UploadBrowseFile(fileInfo[0]); },
    error: function (xhr, status, error) { alert(xhr.responseText); }
});
相关问题