0

I have a from with input of type file I need to get the file data from this form without refreshing the page I'm try to use this function

function submitForm(form){
  var url = $(form).attr("action");
  var formData = {};
  $(form).find("input[name]").each(function (index, node) {
     formData[node.name] = node.value;
  });
  $.post(url, formData).done(function (data) {
     alert(data);
  }); 
}

but this function get the values of form inputs, but I need to get all file data (tmp_name, file_name, file_type ...)
so can any one help me in this please
thanks in advance

1 Answer 1

1

Maybe you can reference your input of type file by id and then get the files property to obtain information about the files. Then you can loop through the files and for example read the name, size and type attribute of the File object.

https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications https://developer.mozilla.org/en-US/docs/Web/API/File

For example

$("#theForm").submit(function(e) {
  submitForm(this);
  e.preventDefault();
});

function submitForm(form) {
  var url = $(form).attr("action");
  var formData = {};
  formData.filesInfo = [];
  var files = $('#inputFile').prop("files");

  $(files).each(function() {
    var fileInfo = {};
    fileInfo.name = this.name;
    fileInfo.size = this.size;
    fileInfo.type = this.type;
    formData.filesInfo.push(fileInfo);
  });

  $.post(url, formData).done(function (data) {
    alert(data);
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="theForm">
    <input type="file" id="inputFile">
    <input type="submit" name="submit" id="submit">
</form>

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

4 Comments

I tried to use the "files" but the page refreshed automatically
When did the page refresh automatically? Did you press a submit button? In the example above I used a form <form id="theForm"> Do you use a different id?
The fourth bird thanks a lot "prop()" method solved the problem thank you very much :)
@MohamedSalah Nice! :) You are welcome. If this solved your problem, maybe you can consider marking the answer as accepted.

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.