Mohamed Salah
Mohamed Salah

Reputation: 166

Upload file data from input of type file in a form using javascript and jquery

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

Upvotes: 0

Views: 121

Answers (1)

The fourth bird
The fourth bird

Reputation: 163352

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>

Upvotes: 1

Related Questions