使用formData上传jQuery文件不起作用

时间:2018-06-19 22:21:56

标签: javascript jquery ajax form-data

我正在尝试使用jquery上传tar文件的简单文件。但是我从服务器获取了无效的存档格式。任何帮助将不胜感激。

PS:我无法更改服务器代码。它来自另一个团队。

编辑1:chrome的回复: enter image description here 我的HTML:

<!DOCTYPE html>
<html>
<body>

<form method="POST" enctype="multipart/form-data" id="testFileUpload">
  <input type="file" name="selectedFile"/>
  <input type="submit" value="Submit" id="btnSubmit"/>
</form>

</body>
</html>

我的JS:

 $(document).ready(function () {
  $("#btnSubmit").click(function (event) {
          event.preventDefault();

        var form = $('#testFileUpload')[0];
    var data = new FormData(form);

    $.ajax({
      type: "POST",
      enctype: 'multipart/form-data',
      url: g_url_version+'/hosting/apps',
      data: data,
      processData: false,
      contentType: false,
      timeout: 600000,
      beforeSend: function (xhr) {
        xhr.setRequestHeader('X-Token-Id', getCookieToken());
        xhr.setRequestHeader('X-Connector-Id', 'TestSeed');
      },
      success: function (data) {
        console.log("SUCCESS : ", data);
      },
      error: function (e) {
        console.log("ERROR : ", e);
      }
    });

  });

});

enter image description here

我可以使用邮递员通过Binary上载文件,如下所示,但不能通过formData。 enter image description here

enter image description here

3 个答案:

答案 0 :(得分:2)

绑定提交事件处理程序,而不要单击按钮,以防止发生 默认表单提交并发送手动ajax调用

 $("#btnSubmit").click(function (event) {

  $("#testFileUpload").on('submit', function(event) {

,只需使用this即可获取其中的表单对象

 var form = this;

复制下面的代码,如果您使用

有一个简单的php文件,则应正确上传文件
print_r($_POST);
print_r($_FILES);

它应该在控制台中显示以下内容

SUCCESS :  Array
(
    [userid] => oemr@omer.com
    [filelabel] => 
)
Array
(
    [file] => Array
        (
            [name] => IMG_20160521_092941676.jpg
            [type] => image/jpeg
            [tmp_name] => F:\xampp\tmp\phpD881.tmp
            [error] => 0
            [size] => 4867779
        )

)

$(document).ready(function() {
  $("#testFileUpload").on('submit', function(event) {

    event.preventDefault();

    var form = this;
    var data = new FormData(form);

    $.ajax({
      type: "POST",
      enctype: 'multipart/form-data',
      url: g_url_version + '/hosting/apps',
      data: data,
      processData: false,
      contentType: false,
      timeout: 600000,
      beforeSend: function(xhr) {
        xhr.setRequestHeader('X-Token-Id', getCookieToken());
        xhr.setRequestHeader('X-Connector-Id', 'TestSeed');
      },
      success: function(data) {
        console.log("SUCCESS : ", data);
      },
      error: function(e) {
        console.log("ERROR : ", e);
      }
    });

  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" enctype="multipart/form-data" id="testFileUpload">
  <input type="file" name="selectedFile" />
  <input type="submit" value="Submit" id="btnSubmit" />
</form>

答案 1 :(得分:0)

您可以通过以下方式尝试: 将您的点击处理程序更新为; jQUERY:

event.preventDefault();
var data = new FormData();
data.append("file",$('input[name="selectedFile"]').files[0]);
// your ajax call looks fine. Use the same.

答案 2 :(得分:-1)

$("#contactform").validate({
    errorClass: "errors_lable",
    rules: {
        email: {
            required: true,
            email: true,
        },
    },
    messages: {
        email: {
            required: "Please enter email address.",
            email: "Please enter Valid email address.",
        },
    },
    submitHandler: function(form) {
        try {
            var formData = new FormData();
            formData.append("LogoName", $('input[type=file]')[0].files[0]);
            formData.append("email", isCollege);
            waitingDialog.show('Please Wait While Processing...');
            $.ajax({
                type: "POST",
                dataType: 'JSON',
                url: "https://code0.ww.com/index.php/...../RegisterSchool",
                data: formData,
                processData: false,
                contentType: false,
                success: function(data) {
                    waitingDialog.hide('Please Wait While Processing...');
                    if (data.ResponseHeader.response_type == 'success') {
                        //                          $('#msg').show();
                        //                          $('#msg').html("<span style='color:#b9efb9'><b>Thankyou For Register</b></span>");
                        alert('Thankyou For Register');
                    } else if (data.ResponseHeader.response_type == 'error') {
                        //$('#msg').show();
                        //$('#msg').html("<span style='color:red'><b>Opps! There is some  error, Please Try again latter.</b></span>");
                        alert('Somithing Went Wrong Please Try Again Latter');
                    }
                },
                error: function(data) {
                    alert('Somithing Went Wrong Please Try Again Latter');
                }
            });
        } catch (err) {
            console.log(err);
        }
    }
});