我无法将我的文件传递给httppostedfilebase in action方法

时间:2015-03-16 04:35:18

标签: javascript jquery asp.net-mvc

我正在使用jquery form plugin将图片传递给我的操作方法。我似乎无法将控制器上的操作方法中的httppostedfilebase设置为正确的数据类型。

$('#imageform').submit(function () {
    var id = $('#selectedFile').data('id');
    //var filename = $('#selectedFile').val(); //.files[0];
    //var filename = document.getElementById('selectedFile').files[0];
    //var filename = input.files[0];
    var filename = $('#selectedFile').prop('files');
    var options = {
        target: '#output',
        enctype: 'multipart/form-data',
        beforeSubmit: showRequest,
        success: showResponse,

        url: '/ManageSpaces/UploadImage',
        data: {
            id: id,
            image: filename[0]
        },
        type: 'post'

    };
    $('#imageform').ajaxSubmit(options);
    return false;
});

这是我的控制器的动作方法。

[HttpPost]
    public ActionResult UploadImage(int id, HttpPostedFileBase image)
    {
        //do some stuff here

        return Json("Saved");
    }

html表单数据

 <form id="imageform" enctype="multipart/form-data">
            <input type="file" id="selectedFile" name="selectedFile" style="display: none;" data-id='@Model.YogaSpaceId' />
            <input type="button" value="Add Photos" class="btn" id="pictureupload" />
        </form>

1 个答案:

答案 0 :(得分:0)

$('#imageform').submit(function () {
    var formData = new FormData();
    var totalFiles = document.getElementById("selectedFile").files.length;
    for (var i = 0; i < totalFiles; i++) {
        var file = document.getElementById("selectedFile").files[i];
        formData.append("FileUpload", file);
    }

    $.ajax({
        type: "POST",
        url: '/Test/UploadImage/', //put your controller/action here
        data: formData,
        dataType: 'json',
        contentType: false,
        processData: false,
        beforeSend: function (xhr) {
             //do something before send
        },
        success: function (data) {
             //do something if success
        },
        error: function (data) {
             //do something if error
        }
    });
});

然后在你的控制器中:

[HttpPost]
public void UploadImage()
{
    if (Request.Files.Count > 0) {
        dynamic file = Request.Files(0);
        //do something with your 'file'
    }
}