symfony 4在表单上没有handleResquest方法但使用xhr对象html上传

Posted

技术标签:

【中文标题】symfony 4在表单上没有handleResquest方法但使用xhr对象html上传【英文标题】:symfony 4 upload without handleResquest method on form but with xhr object html 【发布时间】:2022-01-09 07:37:40 【问题描述】:

你好我想用 xhr html 请求执行我的进度条,用 symfony 4 简单提交是不够的

我尝试使用表单数据对 php 方法执行 xhr html 请求,并使用 e.preventDefault() 指令防止事件默认,但它不起作用。我不知道为什么 Symfony 工具栏说我没问题(代码 200)。但是我无法使用 php 获取输入文件对象。我在这里发布我的代码。

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();
    

我无法保存我的输入文件。

   <div class="col-12">
     form_start(form2,'attr': 'id': 'form2')  
     form_row(form2.file,attr:'placeholder':'veuillez importer votre CV') 
     form_widget(form2) 

    <button type="submit" class="btn btn-primary">Enregistrer!</button>
     form_end(form2) 
        <div class="progress-bar" id="progressBar">
            <div class="progress-bar-fill">
                <span class="progress-bar-text">0</span>
            </div>
        </div>
    </div>
    % if fichier is defined %
        %  for fich fichier %
            <div> fich </div>
        % endfor %
    % endif %
我也有这个错误

【问题讨论】:

【参考方案1】:

我找到了解决办法。

    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);
    

和php代码:

     /**
     ** @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]);
    

【讨论】:

【参考方案2】:

我今天用axios技术试过了,又不行了,在这里,你会看到我的代码js和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']
    );
    

你能帮帮我吗?

【讨论】:

以上是关于symfony 4在表单上没有handleResquest方法但使用xhr对象html上传的主要内容,如果未能解决你的问题,请参考以下文章

Symfony 4.4:为图像文件上传保留的实体/模型属性由表单系统设置更新(结果始终为空 - 没有错误)

如何使用 symfony 4 创建登录验证表单

Symfony 2 在使用没有类的表单时添加 CSRF 令牌

Symfony / Sonata Admin:编辑表单上的列表表单

APC 没有为 Symfony.4/Doctrine 应用程序带来任何性能提升?

Symfony 表单和 Ajax