web-dev-qa-db-ja.com

cakephp2.3でのファイルアップロード

私はcakephpを初めて使用し、cakephp2.3を使用して簡単なファイルアップロードを作成しようとしています。これが私のコントローラーです。

public function add() {
    if ($this->request->is('post')) {
        $this->Post->create();
           $filename = WWW_ROOT. DS . 'documents'.DS.$this->data['posts']['doc_file']['name']; 
           move_uploaded_file($this->data['posts']['doc_file']['tmp_name'],$filename);  


        if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash('Your post has been saved.');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('Unable to add your post.');
        }
     }
 }

そして私のadd.ctp

echo $this->Form->create('Post');
echo $this->Form->input('firstname');
echo $this->Form->input('lastname');
echo $this->Form->input('keywords');
echo $this->Form->create('Post', array( 'type' => 'file'));
echo $this->Form->input('doc_file',array( 'type' => 'file'));
echo $this->Form->end('Submit')

名、姓、キーワード、ファイル名をDBに保存しますが、app/webroot/documentsに保存したいファイルが保存されていません。誰か助けてもらえますか?ありがとう

更新

thaJeztah私はあなたが言ったようにしたが、私が間違っていなければ、ここにいくつかのエラーがありますコントローラーです

public function add() {
     if ($this->request->is('post')) {
         $this->Post->create();
            $filename = WWW_ROOT. DS . 'documents'.DS.$this->request->data['Post']['doc_file']['name']; 
           move_uploaded_file($this->data['posts']['doc_file']['tmp_name'],$filename);



         if ($this->Post->save($this->request->data)) {
             $this->Session->setFlash('Your post has been saved.');
             $this->redirect(array('action' => 'index'));
         } else {
            $this->Session->setFlash('Unable to add your post.');
         }
     }

 }

と私のadd.ctp

 echo $this->Form->create('Post', array( 'type' => 'file'));
 echo $this->Form->input('firstname'); echo $this->Form->input('lastname');
 echo $this->Form->input('keywords');
 echo $this->Form->input('doc_file',array( 'type' => 'file'));
 echo $this->Form->end('Submit') 

そしてエラーは

注意(8):配列から文字列への変換[CORE\Cake\Model\Datasource\DboSource.php、行1005]

データベースエラーエラー:SQLSTATE [42S22]:列が見つかりません:1054 'フィールドリスト'の列 '配列'が不明です

SQLクエリ:INSERT INTO first.posts(firstname、lastname、keywords、doc_file)VALUES( 'dfg'、 'cbhcfb'、 'dfdbd'、Array)

そしてビクター私もあなたのバージョンをやりました、それもうまくいきません。

8
Hovo

投稿されたデータにアクセスするために間違った「キー」を使用しているようです。

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

モデルの「エイリアス」と一致する必要があります。 単数および大文字最初の文字

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

また、_$this->data_は、下位互換性のために_$this->request->data_のラッパーであるため、これを使用することをお勧めします。

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

投稿されたデータの内容を確認し、それがどのように構造化されているかを理解するには、これを使用してデバッグできます。

_debug($this->request);
_

_1_内でdebugを_2_または_app/Config/core.php_に設定して、デバッグを有効にしてください。

更新;フォームタグが重複しています!

コードで複数の(ネストされた)フォームも作成していることに気づきました。

_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'));
_

フォームのネストは決して機能します。その行を削除し、最初のForm->create()に「type => file」を追加します。

データベースにファイルのみを使用name

"配列から文字列への変換"の問題は、データベースに 'doc_file'のデータを直接使用しようとしていることが原因です。これはファイルアップロードフィールドであるため、「doc_file」にはArrayのデータ(「name」、「tmp_name」など)が含まれます。

データベースの場合、必要なのはその配列の「名前」だけなので、データベースに保存する前にデータを変更する必要があります。

exampleの場合、このように;

_// 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;
_
14
thaJeztah

..ドキュメントディレクトリがすでに存在することを確認し、それに書き込む権限があることを確認しますか?存在しない場合は作成するか、コード内に存在するかどうかを確認し、存在しない場合は作成します。ディレクトリが存在するかどうかを確認して作成し、ファイルをアップロードするコードの例-

$dir = WWW_ROOT. DS . 'documents';
 if(file_exists($dir) && is_dir($dir))
 {
    move_uploaded_file($this->data['posts']['doc_file']['tmp_name'],$filename);  
 }
 elseif(mkdir($dir,0777))
 {
  move_uploaded_file($this->data['posts']['doc_file']['tmp_name'],$filename);  
  }

また、空白/空のファイルをアップロードしていないことを確認してください-失敗する可能性があります。

2
Victor

誰かがもう一度それを探している場合に備えて。これが私のコードです(Cakephp 2.5.5でテストおよび使用)。 http://www.templemantwells.com.au/article/website-development/cakephp-image-uploading-with-databasehttp://book.cakephpに基づいています。 .org/2.0/en/core-libraries/helpers/form.html#FormHelper :: file

ファイルの表示(* .ctp)

    <?php 
    echo $this->Form->create('Image', array('type' => 'file'));
?>


    <fieldset>
        <legend><?php echo __('Add Image'); ?></legend>
    <?php


        echo $this->Form->input('Image.submittedfile', array(
            'between' => '<br />',
            'type' => 'file',
            'label' => false
        ));
        // echo $this->Form->file('Image.submittedfile');

    ?>
    </fieldset>
<?php echo $this->Form->end(__('Send My Image')); ?>

コントローラ機能(* .php)

    public function uploadPromotion() {

    // Custom
    $folderToSaveFiles = WWW_ROOT . 'img/YOUR_IMAGE_FOLDER/' ;




    if (!$this->request->is('post')) return;        // Not a POST data!


    if(!empty($this->request->data))
    {
        //Check if image has been uploaded
        if(!empty($this->request->data['Image']['submittedfile']))
        {
                $file = $this->request->data['Image']['submittedfile']; //put the data into a var for easy use

                debug( $file );

                $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions

                //only process if the extension is valid
                if(in_array($ext, $arr_ext))
                {


                    //do the actual uploading of the file. First arg is the tmp name, second arg is 
                    //where we are putting it
                    $newFilename = $file['name']; // edit/add here as you like your new filename to be.
                    $result = move_uploaded_file( $file['tmp_name'], $folderToSaveFiles . $newFilename );

                    debug( $result );

                    //prepare the filename for database entry (optional)
                    //$this->data['Image']['image'] = $file['name'];
                }
        }

        //now do the save (optional)
        //if($this->Image->save($this->data)) {...} else {...}
    }




}
2
Britc

ここからCakePHPでファイルと画像をアップロードするための完全なガイドを見つけました-- CakePHPでのファイルアップロードの処理

サンプルコードを以下に示します。

コントローラー:

$fileName = $this->request->data['file']['name'];
$uploadPath = 'uploads/files/';
$uploadFile = $uploadPath.$fileName;
if(move_uploaded_file($this->request->data['file']['tmp_name'],$uploadFile)){
    //DB query goes here
}

表示:

<?php echo $this->Form->create($uploadData, ['type' => 'file']); ?>
    <?php echo $this->Form->input('file', ['type' => 'file', 'class' => 'form-control']); ?>
    <?php echo $this->Form->button(__('Upload File'), ['type'=>'submit', 'class' => 'form-controlbtn btn-default']); ?>
<?php echo $this->Form->end(); ?>
1
JoyGuru