Data not appending to FormData Object - javascript

I'm trying to upload multiple images for an image upload system using AJAX on Jquery.
However, I'm having trouble getting the FormData object to take in the data from the file input. Here is my code:
HTML:
<form id="multiform" role="form" action="process.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="">
<label for="picture">Upload Pictures</label>
<input type="file" id="pic_upload_file" name="pics[]" multiple>
<input type="button" id="pic_upload" name="pic_upload" value="Upload">
</div>
</div>
</form>
JQuery
$('#pic_upload').click(function(e) {
var formData = new FormData();
formData.append("pics", file);
});
This object is created and I can see it in the console, but I dont know how to get the user file input data into it to send to a php script.
Can anyone help?

You have a file input that takes multiple files, so you have to get those files and append each one to the formData object
$('#pic_upload').on('click', function(e) {
var formData = new FormData(),
files = $('#pic_upload_file').get(0).files;
$.each(files, function(i, file) {
formData.append("pics_" + i, file);
});
$.ajax({
url : 'test.php',
data : formData,
contentType : false,
processData : false,
type : 'POST'
});
});

Related

Make XMLHttpRequest uploader work with multiple files [duplicate]

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.
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/>';
}
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 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...
This worked for me:
let formData = new FormData()
formData.append('files', file1)
formData.append('files', file2)
This one worked for me
//Javascript part
//file_input is a file input id
var formData = new FormData();
var filesLength=document.getElementById('file_input').files.length;
for(var i=0;i<filesLength;i++){
formData.append("file[]", document.getElementById('file_input').files[i]);
}
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData: false,
success: function (html) {
}
});
<?php
//PHP part
$file_names = $_FILES["file"]["name"];
for ($i = 0; $i < count($file_names); $i++) {
$file_name=$file_names[$i];
$extension = end(explode(".", $file_name));
$original_file_name = pathinfo($file_name, PATHINFO_FILENAME);
$file_url = $original_file_name . "-" . date("YmdHis") . "." . $extension;
move_uploaded_file($_FILES["file"]["tmp_name"][$i], $absolute_destination . $file_url);
}
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.
This worked for me
var ins = $('.file').map(function () {
return this.files;
}).get();
for (var x = 0; x < ins; x++) {
formData.append("file", ins[x][0]);
}
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);
}
});
I worked that such as:
var images = document.getElementById('fileupload').files;
var formData = new FormData();
for(i=0; i<images.length; i++) {
formData.append('files', images[i]);
}
If you are instantiating the FormData object already passing the form as a constructor parameter, the input file's name attribute must contain the square brackets.
HTML:
<form id="myForm" method="POST" action="url" enctype="multipart/form-data">
<input class="form-control form-control-lg" type="file" name="photos[]" multiple />
JS:
var formData = new FormData(document.getElementById('myForm'));
console.log(formData.getAll('photos[]'));
That worked for me!
If we have input in our html:
<input id="my-input" type="file" mutliple /> // multiple attribute to select and upload multiple files
We can get files from that input and send it to server with pure js script:
const myInput = document.getElementById('my-input') // getting our input
myInput.addEventListener('change', (event) => { // listening for file uploads
const files = event.target.files // getting our files after upload
const formData = new FormData() // create formData
for (const file of files) {
formData.append('files', file) // appending every file to formdata
}
const URL = 'http://server.com:3000'
const response = fetch(URL, {
method: 'POST',
data: formData // sending our formdata in body of post request
})
return response.json()
}
It worked perfect for me
P.S.: I used multer in backend (node.js + express), added to file upload route
upload.array("files", 10)
First argument is a property name of our files (in formdata)
Second argument is max file size
This worked for me also:
var data = new FormData();
for (const key in files)
data.append('gallery[]',files[key])
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
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
let fd = new FormData();
fd.append( "images" , image1 );
fd.append( "images" , image2 );
fd.append( "images" , image3 );
In this format you can send multiple file by axios.
But i had some problem with this.
only one file was uploaded when i try to append in form data and try to send this through axios.
and my problem was that i had imported {Axios} from 'axios'
but it will not gonna work.
we have to import axios from 'axios'
( look at the spelling )
then it was work perfectly for me
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;
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;
Appending multiple files to the same key didn't work for me. I ended up appending them separately.
files.forEach((file) => {
formData.append(`file-${file.name}`, file);
})

How to send array of file objects through ajax with form serialize()?

I am trying send my form fields along with an array of file objects through ajax call. I used the answer from this question to add/choose multiple files. This answer stores files in an array and sends the files as FormData Object, But in my code i have other forms fields also. I am sending those data from ajax using form.serialize() method. Now i have to send the array of file object together with my all the old data.
let files = []
this above array is array of file objects
So i tried this,
$('#myform').submit(function () {
var formData = new FormData();
files.forEach(file => {
formData.append('file', file);
});
$.ajax({
type: "POST",
url: url,
data: form.serialize() + "&filedata=" + formData,
...
...
})
}
I am using django in the backend, i receive like this,
request.POST.get('filedata')
But using this i receive filedata field as a string "[object FormData]".My question is how to send FormData together with form.serialize()
This is my html:
<form method="POST" action="/" id="myform">
<input type="text" name="name"/>
...
<input type="checkbox" id="option1"/>
<label for="option1">Option 1</label>
...
<select>
<option>Option 1</option>
<option>Option 2</option>
</select>
...
<!--like above checkbox and select elements i have so many other form fields-->
<!--i want to send files array with all the data from above form elements-->
<input id="myInput" type="file" name="files" multiple style="display:none" />
<button id="myButton" type="button">Add Files</button>
<!-- <button id="mySubmitButton" type="button">Upload Files</button> this button is not
required as i want upload files on clicking submit -->
<div id="myFiles"></div>
<input type="submit" />
</form>
I don't want to upload files on clicking upload files button,I want to upload files on clicking submit button together with my text field and files array
If this is not possible how can i send my form fields along with files array to backend?
$('#myform').submit(function () {
var formData = new FormData();
$.each($('#myform')[0].files, function(i, file) {
formData.append('file-'+i, file);
});
$.ajax({
type: "POST",
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST' // jQuery < 1.9
})
}

How to upload a file in Webform using javascript to have it access in global PHP variable $_FILES

I need help and almost crazy. I found a shitload of answers but they all do to work or at least work just a bit !?!
My task is to use a html form and upload one file or more to the webserver using ajax und recieving an answer after evaluation of php. Best I want to send form input information as well as file by an $ajax Request.
I do not understand the syntax.
So can the one or other person ...
a) Tell me how to do correctly one and also a list of files.
How to upload form data and files in one go.
b) What is the structure in detail of the file object
file = $('#file0')[0].files[0] <- I am totally lost, except that
|_____________| '#file0' is the id of the input
? |________| item 'file'
?
in the following piece of code below
Many thanks in advance.
Marvin
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function ajax_file_upload(){
var fd = new FormData();
var file;
// file = $('#file0')[0].files[0]
// fd.append('file0', file);
var formfiles = document.querySelectorAll('[type=file]');
// we start from since the first two input comes from a different form
for (let i = 0; i < formfiles.length; i++) {
var file = formfiles[i].files[0];
var id = 'file' . i;
fd.append( id , file );
alert( file.name );
}
$.ajax({
url: './ajaxupload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
alert(response);
},
error: function(response){
alert("Error occurred while trying to upload file");
}
});
}
</script>
</head>
<body>
<form method="post" action="JavaScript:ajax_file_upload();" enctype="multipart/form-data" id="myform">
<input type="file" id="file0" name="file0" />
<input type="file" id="file1" name="file1" />
<input type="file" id="file2" name="file2" />
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP in script ajaxupload.php:
print_r $_FILES;
I have found the right piece of code I was looking for ...
$.ajax({
...
data: new FormData($('#webform')[0]),
contentType:false,
cache:false,
processData:false,
mimeType: "multipart/form-data",
success: function( upload ){},
...
});

How to properly get form data with JQuery and formData

I am trying to upload some form data using ajax and php but for some reason my data is not being catch or passed.
Here is what I have:
form.html ( basic form with 3 text inputs and 1 file)
<form class="form" id="superform" action="nada.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="tituloQuiz">Resultado:</label>
<input type="text" class="form-control resultado" id="titulo" name="titulo" placeholder="Ex: Paris">
</div>
<div class="form-group">
<label for="desc">Descrição do Site:</label>
<textarea class="form-control" id="desc" name="descricao" placeholder="Ex:"></textarea>
</div>
<div class="form-group">
<label for="desc">OG FB DESC:</label>
<textarea class="form-control" id="facedes" name="descricao" placeholder="facebook description"></textarea>
</div>
<div class="form-group">
<label for="imggrande">Imagem</label>
<input type="file" id="imggrande" name="imgres">
<p class="help-block">Imagem usada na página de resultado e Facebook 600 x 400.</p>
</div>
<button type="button" class="btn btn-primary btn-lg addres">Adicionar Resultado</button>
<button type="button" class="btn btn-danger btn-lg">Próxima Etapa</button>
</form>
And here is the JS that makes the ajax call:
myjs.js
$("document").ready(function(){
$('.row').on('click','.addres',function(){
console.log('Click Detectado');
var formulario = $('#superform');
var formData = new FormData(formulario);
$.ajax({
type: "POST",
url: "addres.php",
data: formData,
async: false,
success: function(data) {
console.log('Funcionou');
},
error: function(data) {
console.log('Erro no formulario');
},
cache: false,
contetType: false,
processData: false
});
});
});
Nothing is being passed and the POST call is empty (See screenshots below).
**addres.php**
<?php
var_dump($_FILES);
var_dump($_POST);
?>
$.ajax({
url: 'address.php',
type: 'POST',
data: new FormData($('#superform')[0]), // The form with the file inputs.
processData: false, // Using FormData, no need to process data.
contentType:false
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multi-part/form one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
read from php using
$_FILES['file-0']
(There is only one file, file-0, unless you specified the multiple attribute on your file input, in which case, the numbers will increment with each file.)
Additional info:
See for yourself the difference of how your formData is passed to your php page by using console.log().
var formData = new FormData($('#superform')[0]);
console.log(formData);
var formDataSerialized = $('#superform').serialize();
console.log(formDataSerialized);
Hope this helps.
extra information read this upload files asynchronously
Note : formData doesn't work in IE 9
You can use .serializeArray() to get the data in array format and then convert it into an object. like this:
function getFormData(formId) {
let formData = {};
let inputs = $('#'+formId).serializeArray();
$.each(inputs, function (i, input) {
formData[input.name] = input.value;
});
return formData;
}

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.
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/>';
}
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 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...
This worked for me:
let formData = new FormData()
formData.append('files', file1)
formData.append('files', file2)
This one worked for me
//Javascript part
//file_input is a file input id
var formData = new FormData();
var filesLength=document.getElementById('file_input').files.length;
for(var i=0;i<filesLength;i++){
formData.append("file[]", document.getElementById('file_input').files[i]);
}
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData: false,
success: function (html) {
}
});
<?php
//PHP part
$file_names = $_FILES["file"]["name"];
for ($i = 0; $i < count($file_names); $i++) {
$file_name=$file_names[$i];
$extension = end(explode(".", $file_name));
$original_file_name = pathinfo($file_name, PATHINFO_FILENAME);
$file_url = $original_file_name . "-" . date("YmdHis") . "." . $extension;
move_uploaded_file($_FILES["file"]["tmp_name"][$i], $absolute_destination . $file_url);
}
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.
This worked for me
var ins = $('.file').map(function () {
return this.files;
}).get();
for (var x = 0; x < ins; x++) {
formData.append("file", ins[x][0]);
}
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);
}
});
I worked that such as:
var images = document.getElementById('fileupload').files;
var formData = new FormData();
for(i=0; i<images.length; i++) {
formData.append('files', images[i]);
}
If you are instantiating the FormData object already passing the form as a constructor parameter, the input file's name attribute must contain the square brackets.
HTML:
<form id="myForm" method="POST" action="url" enctype="multipart/form-data">
<input class="form-control form-control-lg" type="file" name="photos[]" multiple />
JS:
var formData = new FormData(document.getElementById('myForm'));
console.log(formData.getAll('photos[]'));
That worked for me!
If we have input in our html:
<input id="my-input" type="file" mutliple /> // multiple attribute to select and upload multiple files
We can get files from that input and send it to server with pure js script:
const myInput = document.getElementById('my-input') // getting our input
myInput.addEventListener('change', (event) => { // listening for file uploads
const files = event.target.files // getting our files after upload
const formData = new FormData() // create formData
for (const file of files) {
formData.append('files', file) // appending every file to formdata
}
const URL = 'http://api.server.com'
const response = fetch(URL, {
method: 'POST',
data: formData // sending our formdata in body of post request
})
return response.json()
}
It worked perfect for me
P.S.: I used multer in backend (node.js + express), added to file upload route
upload.array("files", 10)
First argument is a property name of our files (in formdata)
Second argument is max file size
This worked for me also:
var data = new FormData();
for (const key in files)
data.append('gallery[]',files[key])
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
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
let fd = new FormData();
fd.append( "images" , image1 );
fd.append( "images" , image2 );
fd.append( "images" , image3 );
In this format you can send multiple file by axios.
But i had some problem with this.
only one file was uploaded when i try to append in form data and try to send this through axios.
and my problem was that i had imported {Axios} from 'axios'
but it will not gonna work.
we have to import axios from 'axios'
( look at the spelling )
then it was work perfectly for me
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;
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;
Appending multiple files to the same key didn't work for me. I ended up appending them separately.
files.forEach((file) => {
formData.append(`file-${file.name}`, file);
})

Categories