hello i want to execute my progressbar with xhr html request , simple submit with symfony 4 is not enough
i try to execute an xhr html request on a php method with a form data , And to prevent event default with e.preventDefault() instruction but it doesn't work .I dont' know why Symfony toolbar say me it's ok (code 200).But i can't get the input file object with php .i post my code here.
var uploadForm=document.getElementById("form2");
uploadForm.addEventListener("submit", uploadFile);
function uploadFile(e) {
e.preventDefault();
var inputFile=document.getElementById("user_file").files[0];
let uploadDataForm = new FormData();
uploadDataForm.append('file',inputFile);
for (var value of uploadDataForm.values()) {
console.log(value);
}
try {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/');
xhr.upload.addEventListener('progress', e => {
const percent = e.lengthComputable ? (e.loaded / e.total) * 100 : 0;
progressBarFill.width = percent.toFixed(2)
progressBarText.textContent=percent.toFixed(2);
});
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send(uploadDataForm);
}
catch (error){
console.error(error);
}
}
/**
* @Route("/", name="acceuil")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function index(Request $request,ProductManager $productManager)
{
/** @var User $user */
$user = new User();
$file = $request->query->get('file');
try {
/** @var UploadedFile $task */
$task = $file;
if ($task === null) exit;
$destination = $this->getParameter('files_directory');
$originalFilename = pathinfo($task->getClientOriginalName(), PATHINFO_FILENAME);
$newFilename = Urlizer::urlize($originalFilename) . '-' . uniqid() . '.' . $task->guessExtension();
//$fileName = md5(uniqid()).'.'.$file->guessClientExtension();
$task->move(
$destination,
$newFilename
// $this->getParameter('files_directory'),
);
return $this->redirectToRoute('acceuil');
} catch (\Exception $e) {
echo $e->getMessage();
}
}
and i can't save my input file .
<div >
{{ form_start(form2,{'attr': {'id': 'form2'}}) }}
{{ form_row(form2.file,{attr:{'placeholder':'veuillez importer votre CV'}}) }}
{{ form_widget(form2) }}
<button type="submit" >Enregistrer!</button>
{{ form_end(form2) }}
<div id="progressBar">
<div >
<span >0</span>
</div>
</div>
</div>
{% if fichier is defined %}
{% for fich fichier %}
<div>{{ fich }}</div>
{% endfor %}
{% endif %}
i have this error too
CodePudding user response:
i tried today with axios technology and it's doesn't work again , here , you will see my code js and after php:
js:
$('document').ready(function () {
const axios = require('axios').default;
const progressBarFill = document.getElementsByClassName('progress-bar-fill');
const progressBarText = document.getElementsByClassName('progressBarText');
var uploadForm = document.getElementById("form2");
$('uploadForm').on('Submit', function (e) {
e.preventDefault();
var inputFile = document.getElementById("user_file").files[0];
let uploadDataForm = new FormData();
uploadDataForm.append('file', inputFile);
var config = {
onUploadProgress: function (e) {
const percent = e.lengthComputable ? (e.loaded / e.total) * 100 : 0;
progressBarText.textContent = percent.toFixed(2);
},
headers: ('X-Requested-width','XMLHttprequest')
};
axios.post('/', uploadDataForm, config).then(function (response) {
console.log(response.data);
});
});
});
// uploadForm.addEventListener("submit", uploadFile);
// function uploadFile(e) {
// e.preventDefault();
// var inputFile=document.getElementById("user_file").files[0];
// let uploadDataForm = new FormData();
// uploadDataForm.append('file',inputFile);
// for (var value of uploadDataForm.values()) {
// console.log(value);
// }
// var coucou = "salut";
// //uploadDataForm.append('file' ,'fichier');
// // $.ajax({
// // type: "POST",
// // url: '/' ,
// // data: {
// // uploadDataForm
// // },
// // enctype: 'multipart/form-data',
// // processData: false,
// // contentType: false,
// // error: function (error){
// // console.error(error);
// // },
// // success: function(response) {
// //
// // }
// // });
//
// try {
// const xhr = new XMLHttpRequest();
// xhr.open('POST', '/');
// xhr.upload.addEventListener('progress', e => {
// const percent = e.lengthComputable ? (e.loaded / e.total) * 100 : 0;
// progressBarFill.width = percent.toFixed(2)
// progressBarText.textContent=percent.toFixed(2);
// });
// xhr.setRequestHeader("Content-Type", "multipart/form-data");
// xhr.send(uploadDataForm);
//
//
// }
// catch (error){
// console.error(error);
// }
//
//
//
//
//
// }
and php:
/**
* @Route("/", name="acceuil")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function index(Request $request,ProductManager $productManager)
{
/** @var User $user */
$user = new User();
$form2 = $this->createForm(UserType::class, $user);
if ($request->query->all()) {
$file = $request->query->get('file');
if ($file === null) exit;
$destination = $this->getParameter('files_directory');
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$newFilename = Urlizer::urlize($originalFilename) . '-' . uniqid() . '.' . $file->guessExtension();
//$fileName = md5(uniqid()).'.'.$file->guessClientExtension();
$file->move(
$destination,
$newFilename
// $this->getParameter('files_directory'),
);
}
// /** @var User $user */
// $user=new User();
// $form2 = $this->createForm(UserType::class, $user);
// $form2->handleRequest($request);
// if ($form2->isSubmitted() && $form2->isValid()) {
// // $form->getData() holds the submitted values
// // but, the original `$task` variable has also been updated
// /** @var UploadedFile $task */
// $task = $form2->get('file')->getData();
// if($task===null) exit;
// $destination = $this->getParameter('files_directory');
// $originalFilename = pathinfo($task->getClientOriginalName(), PATHINFO_FILENAME);
// $newFilename = Urlizer::urlize($originalFilename) . '-' . uniqid() . '.' . $task->guessExtension();
//
// //$fileName = md5(uniqid()).'.'.$file->guessClientExtension();
// $task->move(
// $destination,
// $newFilename
// // $this->getParameter('files_directory'),
//
//
// );
//}
// ... perform some action, such as saving the task to the database
// for example, if Task is a Doctrine entity, save it!
/* $entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($task);
$entityManager->flush();*/
return $this->render( 'acceuil/index.html.twig',[
'products' => $productManager->getProducts(),
'form2' => $form2->createView(),
'fichier'=>$request->query->all(),
'controller_name' => 'AcceuilController']
);
}
could you help me ?
CodePudding user response:
i found the solution.
const progressBarFill = document.getElementsByClassName('progress');
const progressBarText = document.getElementsByClassName('progress-bar');
var uploadForm = document.getElementById("form2");
uploadForm.addEventListener("submit", uploadFile);
function uploadFile(e) {
e.preventDefault();
var inputFile=document.getElementById("user_file").files[0];
let uploadDataForm = new FormData();
uploadDataForm.append('file',inputFile);
for (var value of uploadDataForm.values()) {
console.log(value);
}
try {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/uploadAjax');
xhr.upload.addEventListener('progress', e => {
const percent = e.lengthComputable ? (e.loaded / e.total) * 100 : 0;
$(".progress-bar").width(percent '%');
$(".progress-bar").html(percent '%');
});
xhr.send(uploadDataForm);
console.log(response);
}
}
catch (error){
console.error(error);
}
}
and php code :
/**
** @Route("/uploadAjax", name="uploadAjax")
* @param Request $uneRequete
* @return void
*/
public Function uploadAjax(Request $uneRequete){
try {
$test = 'c bon';
$req = $uneRequete;
/** @var UploadedFile $file */
$file = $uneRequete->files->get('file');
if ($file === null) exit;
$destination = $this->getParameter('files_directory');
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$newFilename = Urlizer::urlize($originalFilename) . '-' . uniqid() . '.' . $file->guessExtension();
//$fileName = md5(uniqid()).'.'.$file->guessClientExtension();
$file->move(
$destination,
$newFilename
);
}
catch (\Exception$e){
echo $e->getMessage();
}
return $this->render('acceuil/index.html.twig',['uneRequete'=>$req]);
}
}