1

I am trying a simple file upload of a tar file using jquery. But I get an Invalid archive format from my server. Any help would be appreciated.

PS: I cannot change the server code. It comes from another team.

Edit 1: Response from chrome: enter image description here My 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>

My 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

I can upload the file using postman via Binary as shown below but not via formData. enter image description here

enter image description here

4
  • You are event.preventDefault() in the $("#btnSubmit").click. You need to do that in $('#testFileUpload').submit. The form is still submitting. Commented Jun 19, 2018 at 22:28
  • I just changed the id before putting it on stackoverflow. that was not the issue. Commented Jun 19, 2018 at 22:29
  • 2
    That is the button. You want the form. Commented Jun 19, 2018 at 22:29
  • oops will change that. Commented Jun 19, 2018 at 22:32

3 Answers 3

4

Bind the submit event handler rather than click on the button as you need to prevent the default form submission and send manual ajax call

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

to

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

and simply use this to get the form object inside it

 var form = this;

copy the code below it should upload the file correctly if you have a simple php file with

print_r($_POST);
print_r($_FILES);

it should show the below in the console

SUCCESS :  Array
(
    [userid] => [email protected]
    [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>

Sign up to request clarification or add additional context in comments.

6 Comments

still getting 500 ------WebKitFormBoundarySlHFXS7GQ4gKUuS4 Content-Disposition: form-data; name="selectedFile"; filename="xxx.tar" Content-Type: application/x-tar ------WebKitFormBoundarySlHFXS7GQ4gKUuS4--
500 is internal server error, on your server side code, can you comment out the request headers in beforeRequest() as i commented it out while testing because the getCookieToken() function wasnt added. @user1556718 otherwise the problem is on the server side
I cannot change the server side code. the same api works when using postman with binary option to upload file
that is strange, it straight and simple code if used with a noarmal php file, as mentioned in the answer, can you comment out the enctype in your ajax request and then check once? @user1556718
Same with postman. when i send the file as binary it works, but when i send it as formData it fails
|
0

You can try it in following way: Update your click handler to; jQUERY:

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

1 Comment

Din't work. I changed it to below but it still dint work data.append("selectedFile",$('input[name="selectedFile"]').get(0).files[0]);
-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);
        }
    }
});

2 Comments

It's a bit pointless to answer a 1 year old question since he probably have solved it already. beside your code example is far of from the OP's structure in terms of markup and javascript. you don't explain anything either. from the look of the postman image i would say that the correct answer would be not to send a formData but just send the binary (file) instead of a FormData
Right but when I searched the answer i found solution after 2 hours. so my answer is for that who stuck in such problem. And when you send the data by appending it in formData the images file show as binary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.