【问题标题】:Upload file in Ajax Form only sends name, not file data在 Ajax 表单中上传文件只发送名称,而不发送文件数据
【发布时间】:2015-11-29 23:50:05
【问题描述】:

好吧,我被难住了。 我有一个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 内容处置:表单数据;名称="文件"

测试.pdf --------------------------4894670511610358147552973488--

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

【问题讨论】:

    标签: javascript ajax html forms file-upload


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 现在试一试,第 1 行缺少一个未闭合的括号')'。
    猜你喜欢
    • 2015-05-22
    • 2017-10-31
    • 2018-02-26
    • 1970-01-01
    • 2014-01-22
    • 2021-08-26
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多