我如何发送带有请求Ajax的图像和表单?

的HTML
    

<input type="text" class="form-control" id="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>

</form>

<button id="btnSave">Save</button>


jQuery-AJAX

$("#btnSave").click(function()
{
    var Url = 'http://localhost/systemm/public/painel/client';

    var Dados = $('#FormClient').serialize();

    $.ajax({
        type:Type,
        url: Url,
        dataType: 'JSON',
        data: Dados,
        success:function(data){
            if($.isEmptyObject(data.error))
                location.reload();
            else
                printErrorMsg(data.error);

        },
        error:function(e){
            alert('Ocorreu um erro !');
            console.log(e);
            },
        });
});


当我序列化数据并显示警报时,我看到该图像不存在,如何将该图像和表单一起发送到server/controller

最佳答案

使用formData对象:

的HTML

<form enctype="multipart/form-data">
    <input type="text" class="form-control" id="Name" name="Name"/>
    <input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
    <button id="btnSave">Save</button>
</form>


JS

$("#btnSave").click(function() {

    var Url = 'http://localhost/systemm/public/painel/client';

    var formData = new FormData(this.form);

    $.ajax({
        type:'post',
        url: Url,
        dataType: 'JSON',
        data: formData,
        ...

    });

});

08-15 18:39