Sending file together with form data via ajax post

前端 未结 3 1788
忘了有多久
忘了有多久 2020-12-05 11:22

I\'m trying to upload a file via ajax together with some fields in a form. However, it doesn\'t work. I get this error.

Undefined Index :- File

3条回答
  •  伪装坚强ぢ
    2020-12-05 12:05

    We need to acknowledge first is that we need to APPEND both Form Input Data and Form File(s) into a single FormData variable.

    Here is my solution in which I have enabled Multi File option so that this solution can fit for all examples.

    It is Important to include name attribute in the input controls to make it work properly on server side in most of cases. If you are using C# then you can use simply Request.Form["nameAttribute"] to simply get the function. It is similar for Java and other languages.

    My Sample Code is

       $(document).ready(function () //Setting up on Document to Ready Function
        {
            $("#btnUpload").click(function (event) {
    
                //getting form into Jquery Wrapper Instance to enable JQuery Functions on form                    
                var form = $("#myForm1");
    
                //Serializing all For Input Values (not files!) in an Array Collection so that we can iterate this collection later.
                var params = form.serializeArray();
    
                //Getting Files Collection
                var files = $("#File1")[0].files;
    
                //Declaring new Form Data Instance  
                var formData = new FormData();
    
                //Looping through uploaded files collection in case there is a Multi File Upload. This also works for single i.e simply remove MULTIPLE attribute from file control in HTML.  
                for (var i = 0; i < files.length; i++) {
                    formData.append(files[i].name, files[i]);
                }
                //Now Looping the parameters for all form input fields and assigning them as Name Value pairs. 
                $(params).each(function (index, element) {
                    formData.append(element.name, element.value);
                });
    
                //disabling Submit Button so that user cannot press Submit Multiple times
                var btn = $(this);
                btn.val("Uploading...");
                btn.prop("disabled", true);
    
                $.ajax({
                    url: "Handler.ashx", //You can replace this with MVC/WebAPI/PHP/Java etc
                    method: "post",
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function () {
                        //Firing event if File Upload is completed!  
                        alert("Upload Completed");
                        btn.prop("disabled", false);
                        btn.val("Submit");
                        $("#File1").val("");
    
                    },
                    error: function (error) { alert("Error"); }
    
                });
    
            });
    
        });
    
    

    For a working example (asp.net C# with handlers) you can visit sample code on https://github.com/vibs2006/HttpFileHandlerFormDataSample

提交回复
热议问题