[javascript] Uploading multiple files using formData()

var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "uph.php");
xhr.send(fd);

uph.php:

var_dump($_FILES['fileToUpload']);

This works, but obviously for the files[0] only. How to get this working for chosen file?

I tried removing the [0], but it didn't work.

This question is related to javascript arrays upload xmlhttprequest

The answer is


Here is the Vanilla JavaScript solution for this issue -

First, we'll use Array.prototype.forEach() method, as

document.querySelectorAll('input[type=file]') returns an array like object.

Then we'll use the Function.prototype.call() method to assign each element in the array-like object to the this value in the .forEach method.

HTML

<form id="myForm">

    <input type="file" name="myFile" id="myFile_1">
    <input type="file" name="myFile" id="myFile_2">
    <input type="file" name="myFile" id="myFile_3">

    <button type="button" onclick="saveData()">Save</button>

</form>

JavaScript

 function saveData(){
     var data = new FormData(document.getElementById("myForm"));
     var inputs = document.querySelectorAll('input[type=file]');

     Array.prototype.forEach.call(inputs[0].files, function(index){
        data.append('files', index);
     });
     console.log(data.getAll("myFile"));
}

You can view the working example of the same HERE


This one worked for me

_x000D_
_x000D_
//Javascript part_x000D_
//file_input is a file input id_x000D_
var formData = new FormData();_x000D_
var filesLength=document.getElementById('file_input').files.length;_x000D_
for(var i=0;i<filesLength;i++){_x000D_
 formData.append("file[]", document.getElementById('file_input').files[i]);_x000D_
}_x000D_
$.ajax({_x000D_
   url: 'upload.php',_x000D_
   type: 'POST',_x000D_
   data: formData,_x000D_
   contentType: false,_x000D_
   cache: false,_x000D_
   processData: false,_x000D_
   success: function (html) {_x000D_
   _x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<?php_x000D_
//PHP part_x000D_
$file_names = $_FILES["file"]["name"];_x000D_
for ($i = 0; $i < count($file_names); $i++) {_x000D_
   $file_name=$file_names[$i];_x000D_
   $extension = end(explode(".", $file_name));_x000D_
   $original_file_name = pathinfo($file_name, PATHINFO_FILENAME);_x000D_
   $file_url = $original_file_name . "-" . date("YmdHis") . "." . $extension;_x000D_
 move_uploaded_file($_FILES["file"]["tmp_name"][$i], $absolute_destination . $file_url);_x000D_
}
_x000D_
_x000D_
_x000D_


You just have to use fileToUpload[] instead of fileToUpload :

fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[0]);

And it will return an array with multiple names, sizes, etc...


I found this work for me!

var fd = new FormData();
$.each($('.modal-banner [type=file]'), function(index, file) {
  fd.append('item[]', $('input[type=file]')[index].files[0]);
});

$.ajax({
  type: 'POST',
  url: 'your/path/', 
  data: fd,
  dataType: 'json',
  contentType: false,
  processData: false,
  cache: false,
  success: function (response) {
    console.log(response);
  },
  error: function(err){
    console.log(err);
  }
}).done(function() {
  // do something....
});
return false;

Adding [] when appending to fd works, but if you prefer to have your data grouped by file then I'd suggest doing it this way:

var files= document.getElementById('inpFile').files
var fd = new FormData()

for (let i = 0; i < files.length; i++) {
  fd.append(i, files[i])
}

Now your data will be sent grouped by file instead of grouped by attribute.


Create a FormData object

const formData: any = new FormData();

And append to the same keyName

photos.forEach((_photoInfo: { localUri: string, file: File }) => {
    formData.append("file", _photoInfo.file);
});

and send it to server

// angular code
this.http.post(url, formData)

this will automatically create an array of object under file

if you are using nodejs

const files :File[] = req.files ? req.files.file : null;

This worked for me:

let formData = new FormData()
formData.append('files', file1)
formData.append('files', file2)

This worked fine !

var fd = new FormData();

$('input[type="file"]').on('change', function (e) {
    [].forEach.call(this.files, function (file) {
        fd.append('filename[]', file);
    });
});

$.ajax({
    url: '/url/to/post/on',
    method: 'post',
    data: fd,
    contentType: false,
    processData: false,
    success: function (response) {
        console.log(response)
    },
    error: function (err) {
        console.log(err);
    }
});

The way to go with javascript:

var data = new FormData();

$.each($("input[type='file']")[0].files, function(i, file) {
    data.append('file', file);
});

$.ajax({
    type: 'POST',
    url: '/your/url',
    cache: false,
    contentType: false,
    processData: false,
    data : data,
    success: function(result){
        console.log(result);
    },
    error: function(err){
        console.log(err);
    }
})

If you call data.append('file', file) multiple times your request will contain an array of your files.

From MDN web docs:

"The append() method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. The difference between FormData.set and append() is that if the specified key already exists, FormData.set will overwrite all existing values with the new one, whereas append() will append the new value onto the end of the existing set of values."

Myself using node.js and multipart handler middleware multer get the data as follows:

router.post('/trip/save', upload.array('file', 10), function(req, res){
    // Your array of files is in req.files
}

You have to get the files length to append in JS and then send it via AJAX request as below

//JavaScript 
var ins = document.getElementById('fileToUpload').files.length;
for (var x = 0; x < ins; x++) {
    fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[x]);
}

//PHP
$count = count($_FILES['fileToUpload']['name']);
for ($i = 0; $i < $count; $i++) {
    echo 'Name: '.$_FILES['fileToUpload']['name'][$i].'<br/>';
}

To upload multiple files with angular form data, make sure you have this in your component.html

Upload Documents

                <div class="row">


                  <div class="col-md-4">
                     &nbsp; <small class="text-center">  Driver  Photo</small>
                    <div class="form-group">
                      <input  (change)="onFileSelected($event, 'profilepic')"  type="file" class="form-control" >
                    </div>
                  </div>

                  <div class="col-md-4">
                     &nbsp; <small> Driver ID</small>
                    <div class="form-group">
                      <input  (change)="onFileSelected($event, 'id')"  type="file" class="form-control" >
                    </div>
                  </div>

                  <div class="col-md-4">
                    &nbsp; <small>Driving Permit</small>
                    <div class="form-group">
                      <input type="file"  (change)="onFileSelected($event, 'drivingpermit')" class="form-control"  />
                    </div>
                  </div>
                </div>



                <div class="row">
                    <div class="col-md-6">
                       &nbsp; <small>Car Registration</small>
                      <div class="form-group">
                        <div class="input-group mb-4">
                            <input class="form-control" 
                (change)="onFileSelected($event, 'carregistration')" type="file"> <br>
                        </div>
                      </div>
                    </div>

                    <div class="col-md-6">
                        <small id="li"> Car Insurance</small>
                      <div class="form-group">
                        <div class="input-group mb-4">
                          <input class="form-control" (change)="onFileSelected($event, 

                         'insurancedocs')"   type="file">
                        </div>
                      </div>
                    </div>

                  </div>


                <div style="align-items:c" class="modal-footer">
                    <button type="button" class="btn btn-secondary" data- 
                  dismiss="modal">Close</button>
                    <button class="btn btn-primary"  (click)="uploadFiles()">Upload 
                  Files</button>
                  </div>
              </form>

In your componenet.ts file declare array selected files like this

selectedFiles = [];

// array of selected files

onFileSelected(event, type) {
    this.selectedFiles.push({ type, file: event.target.files[0] });
  }

//in the upload files method, append your form data like this

uploadFiles() {
    const formData = new FormData(); 

    this.selectedFiles.forEach(file => {
      formData.append(file.type, file.file, file.file.name); 
    });
    formData.append("driverid", this.driverid);

    this.driverService.uploadDriverDetails(formData).subscribe(
      res => {
        console.log(res); 

      },
      error => console.log(error.message)
    );
  }

NOTE: I hope this solution works for you friends


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to upload

Upload file to SFTP using PowerShell This application has no explicit mapping for /error Schedule automatic daily upload with FileZilla jQuery AJAX file upload PHP How to find when a web page was last updated Summernote image upload on change event for file input element Multiple files upload in Codeigniter How to upload files on server folder using jsp How do I measure request and response times at once using cURL?

Examples related to xmlhttprequest

What is difference between Axios and Fetch? Basic Authentication Using JavaScript XMLHttpRequest module not defined/found loading json data from local file into React JS AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource Edit and replay XHR chrome/firefox etc? AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https jQuery has deprecated synchronous XMLHTTPRequest Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest Sending a JSON to server and retrieving a JSON in return, without JQuery