Mitchell Currie
Mitchell Currie

Reputation: 2809

Upload file in Ajax Form only sends name, not file data

Ok I'm stumped. I have an ajax method:

function check_empty() {
    if (document.getElementById('name').value == "" || document.getElementById('email').value == "" || document.getElementById('msg').value == "") {
      alert("Fill All Fields !");
    } else {
      //alert("Will submit form");
      // e.preventDefault();

      $('#spinner').show();
      $('#quote_form').hide();
      $('#submit').hide();

      var formData = new FormData();
      formData.append("file", $("#resume").val());
      $.ajax({
        type: 'post',
        url: '/contact_post.php',
        data: formData,
        success: function(html) {
          alert('Enquiry Submitted. Thank You!');
        },
        error: function(xhr, status, error) {
          var jsonResponseText = $.parseJSON(xhr.responseText);
          var message = '';
          alert('could not submit form: ' + jsonResponseText['message']);
        },

        //Options to tell jQuery not to process data or worry about content-type.
        processData: false,
        contentType: false
      });

    }

And the request params under firefox say: -----------------------------4894670511610358147552973488 Content-Disposition: form-data; name="file"

test.pdf -----------------------------4894670511610358147552973488--

But where's the actual file data? I Can't seem to "send the file", I have PHP on the other end to receive it.

Upvotes: 0

Views: 606

Answers (1)

Chris
Chris

Reputation: 1220

When posting a file using ajax, be sure to get a valid reference to the file. Often this looks like:

formData.append("file", document.getElementById("resume").files[0]);

Also, you may need to set your content-type to handle files, so something like:

ajaxRequest.setRequestHeader("Content-Type", "multipart/form-data");

Upvotes: 1

Related Questions