Sybille Peters
Sybille Peters

Reputation: 3229

How to upload a file with TYPO3 Fluid form.upload and pass it to Extbase controller

I am using the form.upload ViewHelper to upload a file.

<f:form enctype="multipart/form-data" action="list" name="import" object="{import}" method="POST">
    <f:form.upload name="file" property="file" />
    <f:form.submit value="Submit" />
</f:form>

The problem is accessing the file. The $import object contains a file name but the file does not exist.

Upvotes: 2

Views: 4334

Answers (1)

Sybille Peters
Sybille Peters

Reputation: 3229

My problem was, that the file was deleted already when it was handled. I redirected to another action in my controller action and this started a new request.

$this->redirect('list', $import);

The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.

(https://www.php.net/manual/en/features.file-upload.post-method.php)

How file is uploaded is not TYPO3 specific and can be handled differently, see link above.

  • You should also set the temporary path accordingly, see link above.
  • file types can be restricted with accept, e.g. accept='text/csv'

I am using this in a backend module. The following code works.

Fluid

<f:form enctype="multipart/form-data" action="create" name="import" object="{import}" method="POST">
    <f:form.upload name="file" property="file" />
    <f:form.submit value="Submit" />
</f:form>

Model class: Import.php

class Import extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{
    /** @var array */
    protected $file = [];

    /**
     * @return array
     */
    public function getFile()
    {
        return $this->file;
    }

    /**
     * @param array $file
     * @return void
     */
    public function setFile(array $file)
    {
        $this->file = $file;
    }
}

Controller createAction()

/**
 * @param Import $import
 * @return void
 */
public function createAction(Import $import)
{
    $file = $import->getFile(); 
    if ($file) {
        $path = $file['tmp_name'];     
    }
    // ...
}

The action gets called with Import object containing a file property with correctly filled out metadata, e.g.

['name'] = myfile.csv
['type'] = 'text/csv'
['tmp_name'] = '/tmp/hpGLv1E' 
['error'] = 0
['size'] = 51550

Upvotes: 7

Related Questions