在Ajax Form中上传文件只发送名称,而不是文件数据

时间:2015-09-04 00:49:08

标签: javascript ajax html5 forms file-upload

好的,我很难过。 我有一个ajax方法:

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
      });

    }

Firefox下的请求参数说: ----------------------------- 4894670511610358147552973488 内容处理:表格数据; NAME = “文件”

检验.pdf ----------------------------- 4894670511610358147552973488 -

但是实际的文件数据在哪里?我似乎无法“发送文件”,我在另一端有PHP接收它。

1 个答案:

答案 0 :(得分:1)

使用ajax发布文件时,请务必获取对该文件的有效引用。通常这看起来像:

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

此外,您可能需要设置内容类型来处理文件,例如:

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