AJAX文件上传 - HttpPostedFileBase参数始终为null MVC 4

时间:2015-03-25 15:23:57

标签: jquery ajax asp.net-mvc-4 file-upload asp.net-ajax

我正在尝试通过AJAX请求将CSV文件发送到控制器操作,但是HttpPostedFileBase参数始终为null。因此,我无法访问我尝试发送的文件的内容。请有人告诉我我在哪里解决这个问题。

这是我的控制器:

[HttpPost]
public ActionResult ImportCSV(HttpPostedFileBase file)
{
    var files = Request.Files.Count; // This returns 1. However, 'file' parameter is null

    // Process the CSV file here...

    return View();
}

这是我的HTML:

<table class="fieldset">
    <tr>
        <td>Select File:</td>
        <td>
            <!--FILE TEXTFIELD-->
            <input type="file" id="file" name="file" class="hide file-upload" />

            <!--OVERLAY-->
            <div id="filename" class="file-textbox"></div>

            <!--ELIPSES-->
            <button id="filestyle" class="elipses button green-button">...</button>
        </td>
        <td>
            <!--UPLOAD-->
            <button type="button" id="btnUpload" class="button green-button upload">Upload</button>
            <div class="loading"></div>
        </td>
    </tr>
</table>

这是我的JS:

var UploadModule = (function ($) {

"use strict";

var btnElipses;
var btnChangeUpload;
var btnUpload;
var Files = {};

var init = function () {
    btnElipses = $(".elipses");
    btnChangeUpload = $(".file-upload");
    btnUpload = $(".upload");

    bindEvents();
};

var bindEvents = function () {
    btnElipses.on("click", browse);
    btnChangeUpload.on("change", change);
    btnUpload.on("click", upload);
};

var upload = function (e) {

    // Prevent default actions
    e.stopPropagation();
    e.preventDefault();

    // The file object is passed through in the event (hopefully)
    var csv = new FormData();

    // Get file and append to form data
    $.each(Files["csv"], function (key, value) {
        csv.append(key, value);
    });

    // Send file
    $.ajax({
        url: '/Factors/ImportCSV',
        type: 'POST',
        data: csv,
        dataType: "json",
        cache: false,
        contentType: false,
        processData: false,

        success: function (data) {
            //Handle success
        },
        error: function (xhr, status, errorThrown) {
            //Handle error
        }
    });
};

var browse = function (e) {
    $('#file').click();
};

var change = function (e) {
    // Set file name overlay to name of file
    $('#filename').text($(e.target).val().split('\\').pop());

    // Set value of csv to the file
    Files["csv"] = e.target.files;
};

init();

})(jQuery);

1 个答案:

答案 0 :(得分:2)

您可以直接从Request.Files阅读:

 var file = Request.Files[0];

或:

var file = Request.Files["file"];

其中&#34;文件&#34;是输入元素名称

您可能还想阅读this post