Upload file with Cakephp

Asked

Viewed 774 times

3

Regarding the upload file, I have the following codes so far:

Controller:

public
 function initialize()  {
     parent::initialize(); 
     $this - > loadComponent('Upload');
 }

 public
 function upload() {
     if (!empty($this - > request - > data)) {
         $this - > Upload -> send($this - > request - > data['uploadfile']); 
     }
 }

view:

<?php echo $this->Form->create(null, ['type' => 'file']); ?>
            <label>Arquivos</label>
<?php 
    echo $this->Form->file('uploadfile.', ['multiple']);
    echo $this->Form->button('Submit', ['type' => 'submit']);
    echo $this->Form->end();
?>

It’s working, but I need to insert this view within another view (in this case, within a call opening form), which is with that code:

view "add"

<?php
    echo $this->Form->input('id' );
    echo $this->Form->input('titulo');
    echo $this->Form->input('ip');
    echo $this->Form->input('mensagem');
?>

But if I just stick to view that works within the view call opening, no error, but my image upada does not go to the destination folder. I believe it may be something to fix in controller of the "Add" function, its code is like this:

Controller

public
function add() {
    $post = $this -> Posts -> newEntity();
    if ($this -> request -> is(['post', 'put'])) {
        $this -> Posts -> patchEntity($post, $this - > request - > data);
        $post -> user_id = $this - > Auth -> user('id');


        if ($this -> Posts -> save($post)) {
            $this -> Flash -> success(__('Chamado enviado, aguarde resposta... '));
            return $this -> redirect(['action' => 'listar']);
        }
        $this -> Flash -> error(__('Chamado não enviado'));
    }
    $this -> set(compact('post'));

} 

I think if I could call the "upload" function inside the "add" function, it would solve the problem, but how can I do that?

  • Where are you setting up the upload path?

  • You say, the path in which the files will be saved? If so, I am configuring in the Component, "Uploadcomponent"

  • I don’t know how Cakephp works, since I use Codeigniter more often, but I think it had to have the PHP function move_uploaded_file somewhere in there, no?

  • Yes, but within the Uploadcomponent class: move_uploaded_file($file_tmp_name, $dir.DS.Text::uuid(). '-'. $filename);

1 answer

1

You must keep the ['type' => 'file'] as one of the parameters present in the create() method when creating a form that must upload files, otherwise the file will not be transferred.

  • Exactly, as you went through: <?php echo $this->Form->create(null, ['type' => 'file']); ?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.