简体   繁体   中英

Symfony file upload “Error: Call to a member function getClientOriginalName() on null”

I am working on a Symfony form with file uploads. However when I upload a smaller file it works properly but with a bigger file say 8MB file it gives the following error for using getClientOriginalName() or guessClientExtension().

Error: Call to a member function getClientOriginalName() on null

This is the Twig Form

<form method="post" role="form" {{form_enctype(form)}}>
    {{form_widget(form.file)}}
    {{form_errors(form.file) }}
    {{form_rest(form)}}
    <button class="btn btn-primary" type="submit">Upload</button>
</form>

IndexController.php

public function indexAction() {
    $form = $this->createFormBuilder()
        ->add('file', 'file')
        ->getForm();

    $request = $this->getRequest();
    if ($request->getMethod() == 'POST') {
        $form->bind($request);
        $upload_file = $form['file']->getData();

        $ext = strtolower(pathinfo($upload_file->getClientOriginalName(), PATHINFO_EXTENSION));

        if (!in_array($ext, array("csv", "xlsx", "xls"))) {
            $form->get("file")->addError(new FormError("Invalid file format"));
        }

        if ($form->isValid()) {
            if ($upload_file) {
                $upload_file_name = $this->getUser()->getId() . "_" . date("ymdHis") . "." . $ext;
                $upload_file->move("uploads", $upload_file_name);
            }
        }
    }

    return $this->render('AppBundle:Index:index.html.twig', array('form' => $form->createView()));
}

I have set upload_max_size in php.ini to 64MB and increased the max_execution_time as well. What am I doing wrong here? It works with smaller files but not with a file of 8MB. Please help.

You have to change as following:

memory_limit = ?M
upload_max_filesize = ?M
post_max_size = ?M

If the upload_max_filesize is larger than post_max_size, you must increase post_max_size so that it is bigger than upload_max_size.

If the value of post_max_size is larger than memory_limit, you must increase memory_limit so that it is larger than post_max_size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM