Pergunta

I am using cakephp 2.4.1 for my project.I am having two tables casts and castimage. Now castimage having two columns cast id and cast_image_path. now i have to upload image with respective to cast id and store it in different folders according to cast ids? so how would i do that and how i store the image path in database?

Foi útil?

Solução

You add in your view file

view.ctp

<?php if (!empty($this->data['Contact']['filepath'])): ?>
<div class="input">
    <label>Uploaded File</label>
    <?php
    echo $this->Form->input('filepath', array('type'=>'hidden'));
    echo $this->Html->link(basename($this->data['Contact']['filepath']), $this->data['Contact']['filepath']);
    ?>
</div>
<?php else: ?>
<?php echo $this->Form->input('filename',array(
    'type' => 'file'
)); ?>

In your controller

    public function add(){
    if ($this->request->is('post')) {
        // create
        $this->Castimage->create();

        // attempt to save
        if ($this->Castimage->save($this->request->data)) {
            $this->Session->setFlash('image has been successfully saved!');
            $this->redirect(array('action' => 'index'));

        // form validation failed
        } else {
            // check if file has been uploaded, if so get the file path
            if (!empty($this->Castimage->data['Castimage']['filepath']) && is_string($this->Castimage->data['Castimage']['filepath'])) {
                $this->request->data['Castimage']['filepath'] = $this->Castimage->data['Castimage']['filepath'];
            }
        }
    }
}

Outras dicas

This plugin will do what you want: https://github.com/josegonzalez/cakephp-upload

$cast_id = $this->request->data['Image']['cast_id];

if directory is not created, create new one

if(!is_dir($cast_id) {
$oldumask = umask(0);
mkdir($cast_id, 0777);
umask($oldumask);
}

$uniq = mt_rand();
    move_uploaded_file($this->requset->data['Image']['tmp_name'],WWW_ROOT.DS.$cast_id.DS.$uniq.'.'$this->request->data['Image']['name']);

I hope it gives you some idea

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top