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
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
//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_
<?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_
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.
"The
append()
method of theFormData
interface appends a new value onto an existing key inside aFormData
object, or adds the key if it does not already exist. The difference betweenFormData.se
t andappend()
is that if the specified key already exists,FormData.set
will overwrite all existing values with the new one, whereasappend()
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">
<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">
<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">
<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">
<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
Source: Stackoverflow.com