file upload in cakephp 2.3

前端 未结 4 1667
庸人自扰
庸人自扰 2020-12-18 01:11

I\'m new in cakephp and i\'m trying to create a simple file upload with cakephp 2.3 here is my controller

public function add() {
    if ($this->request-&         


        
4条回答
  •  一整个雨季
    2020-12-18 01:23

    You seem to be using the wrong 'key' to access the posted data;

    $this->data['posts'][....
    

    Should match the 'alias' of you Model; singular and a captial first letter

    $this->data['Post'][....
    

    Also, $this->data is a wrapper for $this->request->data for backwards compatibility, so it's better to use this;

    $this->request->data['Post'][...
    

    To check the content of the posted data and understand how it's structured, you may debug it using this;

    debug($this->request);
    

    Just be sure to enable debugging, by setting debug to 1 or 2 inside app/Config/core.php

    Update; duplicate Form tags!

    I just noticed you're also creating multiple (nested) forms in your code;

    echo $this->Form->input('keywords');
    
    // This creates ANOTHER form INSIDE the previous one!
    echo $this->Form->create('Post', array( 'type' => 'file'));
    
    echo $this->Form->input('doc_file',array( 'type' => 'file'));
    

    Nesting forms will never work, remove that line and add the 'type => file' to the first Form->create()

    Using only the file name for the database

    The "Array to string conversion" problem is cause by the fact that you're trying to directly use the data of 'doc_file' for your database. Because this is a file-upload field, 'doc_file' will contain an Array of data ('name', 'tmp_name' etc.).

    For your database, you only need the 'name' of that array so you need to modify the data before saving it to your database.

    For example this way;

    // Initialize filename-variable
    $filename = null;
    
    if (
        !empty($this->request->data['Post']['doc_file']['tmp_name'])
        && is_uploaded_file($this->request->data['Post']['doc_file']['tmp_name'])
    ) {
        // Strip path information
        $filename = basename($this->request->data['Post']['doc_file']['name']); 
        move_uploaded_file(
            $this->data['Post']['doc_file']['tmp_name'],
            WWW_ROOT . DS . 'documents' . DS . $filename
        );
    }
    
    // Set the file-name only to save in the database
    $this->data['Post']['doc_file'] = $filename;
    

提交回复
热议问题