We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Image Uploading Problem.

I want to upload image in my database. I want to upload that image with some form element. but i don't know how can i do that. my Controller is there.

public function createAction() {

    if ($this->request->isPost()) { 

        $blog = new Blogs();

        $blog->assign(array(
            'title' => $this->request->getPost('title', 'striptags'),
            'description' => $this->request->getPost('description'), 
            //here i want to add upload image...
        ));

        //get current user name
        $blog->name = $this->getName();

        //var_dump($blog);exit;

        if (!$blog->save()) {
            $this->flash->error($blog->getMessages());
        } else {

            $this->flash->success("Blogs was created successfully");

            Tag::resetInput();
        }
    }

    $this->view->form = new BlogsForm(null);
}

Please try a search before posting on the forums...

https://forum.phalcon.io/discussion/396/uploading-files



2.3k
Accepted
answer

solve my problem.

here is my controller.

public function imguploadAction() {
if ($this->request->hasFiles() == true) { $baseLocation = 'files/';

        // Print the real file names and sizes
        foreach ($this->request->getUploadedFiles() as $file) {

            $photos = new Photo();              

            $unique_filename = $this->get_random_filename();

            $photos->size = $file->getSize();
            $photos->original_name = $file->getName();
            $photos->file_name = $unique_filename;
            $photos->extension = $file->getExtension();

            if (!$photos->save()) {
                $this->flash->error($photos->getMessages());
            } else {

                $this->flash->success("Blogs was created successfully");
                //Move the file into the application
                $file->moveTo($baseLocation . $unique_filename . "." . $file->getExtension());                    
            }
        }
        //var_dump($file);exit();
    }

}
public function get_random_filename()
{
    $length = 20;
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));

    for ($i = 0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }

    return $key;
}

and my model is here.

<?php namespace Vokuro\Models;

use Phalcon\Mvc\Model; use Phalcon\Mvc\Model\Validator\Uniqueness;

/**

  • Vokuro\Models\Users
  • All the users registered in the application */ class Photo extends Model { /*

    • @var integer */ public $id;

    /*

    • @var string */ public $original_name;

    /*

    • @var string */ public $file_name;

    /*

    • @var string */ public $extension;

    /*

    • @var integer */ public $size; }

Please accept your own answer so the thread will be marked as solved ;]