如何插入文件csv symfony 4

时间:2019-05-22 12:18:03

标签: php symfony symfony-4.2

我是symfony 4的初学者:),我想通过symfony 4中的输入文件在我的数据库中插入一个CSV文件

我尝试在控制器中执行某些操作,但是他将file.csv转换为file.txt,我不明白为什么?

public function upload(Request $request): Response
{

    $upload     = new Upload();
    $formUpload = $this->createForm(UploadType::class, $upload);
    $formUpload->handleRequest($request);
    if ($formUpload->isSubmitted() && $formUpload->isValid()) {

        $file     = $upload->getUpload();
        $fileName = md5(uniqid()).'.'.$file->guessExtension();
        $file->move($this->getParameter('upload_directory'), $fileName);
        $upload->setUpload($fileName);

        $reader = Reader::createFromPath('%kernel.root.dir%/../public/uploads/'.$fileName);
        $result = $reader->fetchAssoc();
        foreach ($result as $row){
            $customer = new Customers();
            $customer
                ->setCivility($row['civility'])
                ->setLastName($row['last_name'])
                ->setFirstName($row['first_name'])
                ->setEmail($row['email'])
                ->setNumber($row['number'])
                ->setDealer($row['dealer'])
                ->setDealerCode($row['dealer_zone'])
                ->setDealerZone($row['dealer_code'])
            ;
            $this->em->persist($customer);

        }
        $this->em->flush();
        $this->addFlash('success','Bien ajouté avec succès');
    }
    return $this->render('customers/upload.html.twig',[
        'formUpload' => $formUpload->createView()
    ]);
}

1 个答案:

答案 0 :(得分:1)

尝试使用$file->getClientOriginalExtension()代替$file->guessExtension()