Upload file using Ajax call using ASP.NET MVC

前端 未结 2 1119
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-06 03:28

I would like to upload a file in my page using:


I have a button, clicking on which an ajax po

2条回答
  •  盖世英雄少女心
    2021-01-06 04:23

    jquery Forms plugin (GitHub Link)would be an ideal choice in this context. You can simply do it like this. (Include the file input in this form)

    $('#myFormId').submit(function() { 
        // submit the form 
        $(this).ajaxSubmit(); 
        // return false to prevent normal browser submit and page navigation 
        return false; 
    });
    

    Demo

    This would be a No plugin approach (only in Html5), but I'm still recommending the plugin

    $("#myFormId").submit(function(){
    
        var formData = new FormData($(this)[0]);
    
        $.ajax({
            url: "YourPath/ToAction",
            type: 'POST',
            data: formData,
            async: false,
            success: function (data) {
                alert(data)
            },
            cache: false,
            contentType: false,
            processData: false
        });
    
        return false;
    });
    

    Another nice plugin.

提交回复
热议问题