13

html markup:

<input id="fileSelect" type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />

I am uploading multiples files with php. I want to make an array of upload files and send to server with ajax. how to make an array of the multiple selected files?

JavaScript:

jQuery.ajax({
    url: 'insertfiles.php',
    type: "POST",
    data: {
      file: // array of selected files.
    },
    success: function(data){
    },
    error: function(data){
      alert( 'Sorry.' );
    }
});
2

3 Answers 3

12

Use the code below.

var formData = new FormData($("#formid")[0]);
jQuery.ajax({
  url: 'insertfiles.php',
  type: "POST",
  data: formData,
  success: function(data) {
        
  },
  error: function(data) {
    alert( 'Sorry.' );
  },
  cache: false,
  contentType: false,
  processData: false,
});

Hope this helps you

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

6 Comments

This will send both text and files
[object FormData] how to check the data in alert()?
could you please explain var formData = new FormData($("#formid")[0]);
@KanishkaBKodithuwakku Just have a look at this documentation. developer.mozilla.org/en-US/docs/Web/API/FormData/…
Great! Worked for me. Keep in mind -data- in success call back must be JSON parsed in order to access its goodies: var myobj = JSON.parse(data);
|
8

Modern browsers that support the HTML5 file stuff have in the <input> element a "files" property. That will give you a file list reference, which has a length property.

As the property is already an array so you just need to access it or iterate through it.

JS

var input = document.getElementById('id');
console.log(input.files);

for (var i = 0; i < input.files.length; i++) {
 console.log(input.files[i]);
}

3 Comments

alert( input.files[i] ) giving me object. is it right?
@HassanAli yes is correct, it is an array of File objects, each file has properties like name, type and size. Try alert( input.files[i].name);
one question do i send array using input.files[i].name or input.files[i]?
4
var formData = new FormData(this);
debugger;
$.ajax({
  url: formURL,
  type: 'POST',
  data: formData,
  mimeType: "multipart/form-data",
  contentType: false,
  cache: false,
  processData: false,
  success: function (data, textStatus, jqXHR) {
    debugger;
  },
  error: function (jqXHR, textStatus, errorThrown) {
                    
  }
});

The above code will help you post content plus files in one submit call.

The post method parameter should include HttpPostedFileBase[] file so the list of files will appear in this file parameter

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.