简体   繁体   中英

JQuery ajax file upload to ASP.NET with all form data

I am building a website, that has a career page with Input File HTML Control for Resume uploading. While using JQuery to POST the form values to an ASPX Page, Everything works fine except File uploading. How can I Use JQuery to Post every fields (including files) in one AJAX request ? The example I see in Google are handling only the file uploading, not other fields with it. This is my JQuery, ASPX for file upload not made.

  <script type="text/javascript">

   $(document).ready(function(e) {

       // File variable
       var files;

       // Add events
       $('#resume').on('change', prepareUpload);

       // Grab the files and set them to our variable
       function prepareUpload(event)
       {
         files = event.target.files;
       }



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

       var fileData = new FormData();
       $.each(files, function(key, value)
       {
           fileData.append(key, value);
       });



       var formMessage = tinyMCE.get('message').getContent();
       var formName = $('.contact-container #name').val();
       var formPhone = $('.contact-container #phone').val();
       var formEmail = $('.contact-container #email').val();
       var formApplyFor = $('.contact-container #applyfor').val();

    // Get some values from elements on the page:
   var a=  $.ajax({
           method: "POST",
           url: "mail/test.aspx",
           processData: false,
           contentType: false,
           data: {
                   form: 'career',
                   name: formName ,
                   phone: formPhone,
                   email: formEmail,
                   applyfor: formApplyFor,
                   resume: fileData,
                   coverletter: window.btoa(unescape(encodeURIComponent( formMessage)))
                   },

                   success: function (data) {
                   alert('success');

               },
               error: function (data) {
                   alert('err');

               }
       })
       .done(function( msg ) {
           alert('done');
       }); //ajax end
   alert(a);

   }); //submit button end

   }); //document ready end
 </script>

It is probably because you should not treat it separately but rather as one form object (formData)

Here you can find an example with form containing both "primitive" fields aswell as file field

https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

I did a quick test to demonstrate it works using ASP.NET MVC:

HTML and Javascript:

<form id="form" name="form1" method="post" enctype="multipart/form-data">
    <div>
        <label for="caption">Image Caption</label>
        <input name="caption" type="text" />
    </div>
    <div>
        <label for="caption2">Image Caption2</label>
        <input name="caption2" type="text" />
    </div>
    <div>
        <label for="image1">Image File</label>
        <input name="image1" type="file" />
    </div>
</form>

<button onclick="submit()">test</button>

function submit() {
    var form = document.querySelector('form');

    var data = new FormData(form);

    $.ajax({
        type: "POST",
        url: "Home/Upload",
        data: data,
        processData: false,
        contentType: false
    });
}

ASP.NET MVC:

    public ActionResult Upload()
    {
        foreach (string file in Request.Files)
        {
            var fileContent = Request.Files[file];
            if (fileContent != null && fileContent.ContentLength > 0)
            {
                var stream = fileContent.InputStream;
                var fileName = fileContent.FileName;
                //you can do anything you want here
            }
        }

        foreach (string key in Request.Form)
        {
            var value = Request.Form[key];
        }

        return Content("OK");
    }

在此输入图像描述

Of course it could be done better by binding to a model, etc...

If your primitive fields are not inside a form I would use append to add them to formData object and then try to send just this object alone. Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM