Cannot get CakePHP 3.8 multiple file upload to work

227 Views Asked by At

I'm working on this project and at first it has a single file upload that works perfectly fine, but had to change to multiple file upload and now I just can't make it work! Getting an "Headers aready sent" error:

Deprecated (16384): Accessing `here` as a property will be removed in 4.0.0. Use request->getAttribute("here") instead. - /home1/thecyb80/seibo.the-cyberpunk.com/src/Controller/AppController.php, line: 92
 You can disable deprecation warnings by setting `Error.errorLevel` to `E_ALL & ~E_USER_DEPRECATED` in your config/app.php. [CORE/src/Core/functions.php, line 311]

Warning (512): Unable to emit headers. Headers sent in file=/home1/thecyb80/seibo.the-cyberpunk.com/vendor/cakephp/cakephp/src/Error/Debugger.php line=856 [CORE/src/Http/ResponseEmitter.php, line 51]

Warning (2): Cannot modify header information - headers already sent by (output started at /home1/thecyb80/seibo.the-cyberpunk.com/vendor/cakephp/cakephp/src/Error/Debugger.php:856) [CORE/src/Http/ResponseEmitter.php, line 152]

Warning (2): Cannot modify header information - headers already sent by (output started at /home1/thecyb80/seibo.the-cyberpunk.com/vendor/cakephp/cakephp/src/Error/Debugger.php:856) [CORE/src/Http/ResponseEmitter.php, line 185]

Warning (2): Cannot modify header information - headers already sent by (output started at /home1/thecyb80/seibo.the-cyberpunk.com/vendor/cakephp/cakephp/src/Error/Debugger.php:856) [CORE/src/Http/ResponseEmitter.php, line 185]

Here's my code: add.ctp

<?= $this->Form->create($atividade, ['type' => 'file']) ?>

[...]

<div class="form-group m-0">
    <label class="btn btn-light p-3 rounded border d-flex align-items-center justify-content-center flex-column" style="cursor: pointer; min-height: 350px;">
        <strong class="d-block">Selecione o(s) arquivo(s) da atividade. Você pode enviar até 10 arquivos.</strong>
        <span class="exercicio-nome d-flex aling-items-center justify-content-center w-100 mt-3"></span>
        <?= $this->Form->file('arquivos[]', [ 'class' => 'exercicio-item', 'multiple' => 'multiple', 'style' => 'display: none;', 'label' => [ 'class' => 'd-none' ] ]) ?>
    </label>
</div>

Validation founded in AtividadesTable.php (that's the only occurrence of the field):

$validator
    ->scalar('arquivos')
    ->maxLength('arquivos', 255)
    ->allowEmptyString('arquivos')
    ->allowEmptyFile('arquivos');

I've tried several solutions, that I've found over the internet, but none helped me. I'm using CakePHP 3.8.11 over PHP 7.2.31.

Here'se my composer.json modules installed (don't know if it can help):

"require": {
    "php": ">=5.6",
    "cakephp/cakephp": "3.8.*",
    "cakephp/migrations": "^2.0.0",
    "cakephp/plugin-installer": "^1.0",
    "mobiledetect/mobiledetectlib": "2.*"
}

Since I can't go over this step, I'm assuming that for now, my Controller is irrelevant. What can I do?


Edit: 06/04 (asked by Salines)

Multiple file upload (uploaded 4 files)

Using

<?= $this->Form->file('arquivos[]', [ 'class' => 'exercicio-item', 'multiple' => 'multiple', 'style' => 'display: none;', 'label' => [ 'class' => 'd-none' ] ]) ?>

Output

(Page just refreshs)

Single file upload

Using

<?= $this->Form->file('arquivos[]', [ 'class' => 'exercicio-item', 'multiple' => 'multiple', 'style' => 'display: none;', 'label' => [ 'class' => 'd-none' ] ]) ?>

Output

(Page just refreshs)

Multiple file upload (uploaded 4 files)

Using

<?= $this->Form->file('arquivos', [ 'class' => 'exercicio-item', 'multiple' => 'multiple', 'style' => 'display: none;', 'label' => [ 'class' => 'd-none' ] ]) ?>

Output

 /src/Controller/AtividadesController.php (line 159)

[
    'nome' => 'Atividade teste',
    'status' => '1',
    'users' => [
        '_ids' => [
            (int) 0 => '306'
        ]
    ],
    'turmas' => [
        '_ids' => [
            (int) 0 => '17'
        ]
    ],
    'materias' => [
        '_ids' => [
            (int) 0 => '45'
        ]
    ],
    'descricao' => '<p>Teste</p>
',
    'comeca_dia' => [
        'year' => '2020',
        'month' => '06',
        'day' => '04'
    ],
    'termina_dia' => [
        'year' => '2020',
        'month' => '06',
        'day' => '04'
    ],
    'video' => '',
    'aviso_do_professor' => 'Teste',
    'arquivos' => [
        'tmp_name' => '/tmp/phpafKkWr',
        'error' => (int) 0,
        'name' => 'imagem_sobre.png',
        'type' => 'image/png',
        'size' => (int) 600995
    ]
]

Multiple file upload (uploaded 4 files)

Using

<?= $this->Form->file('arquivos. ', [ 'class' => 'exercicio-item', 'multiple' => 'multiple', 'style' => 'display: none;', 'label' => [ 'class' => 'd-none' ] ]) ?>

Output

(Page just refreshs)

AtividadesController

I'll show my AtividadesController.php (add method):

/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add($nivelId = null)
{
    $atividade = $this->Atividades->newEntity();

    if ($this->request->is('post')) {

        // Edit - StackOverflow
        debug($this->getRequest()->getData()); exit;

        $atividade = $this->Atividades->patchEntity($atividade, $this->request->getData());

        die(debug($_FILES));

        // Salvando os arquivos
        if (!empty($_FILES['arquivos']['name'])) {
            $file = $_FILES['arquivos'];
            $arquivoName = $file['name'];
            $userId = $this->Auth->user('id');

            $ext = substr(strtolower(strrchr($arquivoName, '.')), 1);
            $arr_ext = array('zip', 'rar', 'pdf', 'doc', 'docx', 'ppt', 'pptx');

            if (in_array($ext, $arr_ext)) {
                $imgHashed = md5($arquivoName) . time() . '.' . $ext;
                $fileDir = WWW_ROOT . 'files/' . $userId;

                if (!is_dir($fileDir)) {
                    mkdir($fileDir);
                }

                @move_uploaded_file($file['tmp_name'], $fileDir . '/' . $imgHashed);

                $atividade['arquivos'] = $imgHashed;
                $atividade['arquivo_nome'] = $arquivoName;
            } else {
                $this->Flash->error(__("Só aceitamos imagens dos tipos 'zip', 'rar', 'pdf', 'doc', 'docx', 'ppt' ou 'pptx'."));

                return $this->redirect(['action' => 'add']);
            }
        }

        if ($this->Atividades->save($atividade)) {
            $this->Flash->success(__('A atividade foi salva.'));

            return $this->redirect(['action' => 'index', $this->Auth->user('id')]);
        }
        $this->Flash->error(__('A atividade não pode ser salva. Por favor, tente novamente.'));
    }

    $arquivos = $this->Atividades->Arquivos->find('list');
    $materias = $this->Atividades->Materias->find('list');

    if ($nivelId) {
        $turmas = $this->Atividades->Turmas->find('list')->matching('Nivels', function($q) use ($nivelId) {
            return $q
                ->select()
                ->where(['Nivels.id' => $nivelId]);
        });
    } else {
        $turmas = $this->Atividades->Turmas->find('list');
    }
    $users = $this->Atividades->Users->find('list')->where(['tipo' => 'professor']);
    $this->set(compact('atividade', 'arquivos', 'materias', 'turmas', 'users'));
}

Am I missing something? Some CakePHP component, maybe? Some PHP extension?

0

There are 0 best solutions below