Uploading both data and files in one form using Ajax?

后端 未结 10 850
无人共我
无人共我 2020-11-21 05:48

I\'m using jQuery and Ajax for my forms to submit data and files but I\'m not sure how to send both data and files in one form?

I currently do almost the same with b

10条回答
  •  悲&欢浪女
    2020-11-21 06:35

    For me following code work

    $(function () {
        debugger;
        document.getElementById("FormId").addEventListener("submit", function (e) {
            debugger;
            if (ValidDateFrom()) { // Check Validation 
                var form = e.target;
                if (form.getAttribute("enctype") === "multipart/form-data") {
                    debugger;
                    if (form.dataset.ajax) {
                        e.preventDefault();
                        e.stopImmediatePropagation();
                        var xhr = new XMLHttpRequest();
                        xhr.open(form.method, form.action);
                        xhr.onreadystatechange = function (result) {
                            debugger;
                            if (xhr.readyState == 4 && xhr.status == 200) {
                                debugger;
                                var responseData = JSON.parse(xhr.responseText);
                                SuccessMethod(responseData); // Redirect to your Success method 
                            }
                        };
                        xhr.send(new FormData(form));
                    }
                }
            }
        }, true);
    });
    

    In your Action Post Method, pass parameter as HttpPostedFileBase UploadFile and make sure your file input has same as mentioned in your parameter of the Action Method. It should work with AJAX Begin form as well.

    Remember over here that your AJAX BEGIN Form will not work over here since you make your post call defined in the code mentioned above and you can reference your method in the code as per the Requirement

    I know I am answering late but this is what worked for me

提交回复
热议问题