我无法在操作方法中将我的文件传递给 httppostedfilebase

I can't pass my file to httppostedfilebase in action method

本文关键字:文件 httppostedfilebase 我的 操作方法      更新时间:2023-09-26

我正在使用jquery表单插件将图像传递给我的操作方法。我似乎无法将控制器上的操作方法中的 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>
$('#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'
    }
}