Yii Framework Forum

Upload Image Without Model


(Mstdmstd) #1

Hello,

here http://www.yiiframework.com/wiki/349/how-to-upload-image-photo-and-path-entry-in-database-with-update-functionality/ I found an article

how to upload an image for model. It works for me with some changes.

But also if can I upload images which has no related model->fieldname. I mean product has many images, which are just uploaded in its directory, but they have no related database table. Class CUploadedFile used in this article works with model.

I remember about native php move_uploaded_file function, but I suppose that it is much better to use yii methods.

Also using move_uploaded_file I have to track Slashes in case OS is windows( say if developer works under windows ).

yii methods do this automaticcaly ? Please give reference to example how to do this.


(Joe) #2

Create a standard uploadform with a filefield named ‘file’.

In the controller upload action you can use


$uploadedFile = CUploadedFile::getInstanceByName('file');

instead of $uploadedFile = CUploadedFile::getInstance($model,$attribute);


(Joe) #3

In the upload view you can do like:




echo CHtml::beginForm('', 'post', array('enctype' => 'multipart/form-data'));

echo CHtml::fileField('file');

echo CHtml::submitButton('Upload');

echo '</form>';





(Mstdmstd) #4

Is getInstanceByName good for uploading Files ?

I make :


  $src_filename= $_FILES['Good']['tmp_name']['img_thumb'];

  echo '<pre>$src_filename::'.print_r($src_filename,true).'<pre>'; // I saw valid file path

  if (file_exists($src_filename)) {

    echo '<pre>$src_filenameEXISTS::'.print_r($src_filename,true).'<pre>';  // it shoes me that file exists!

  }

  $uploadedFile = CUploadedFile::getInstanceByName($src_filename);

  echo '<pre>111$uploadedFile::'.print_r($uploadedFile,true).'<pre>'; // But CUploadedFile object is empty !



Which is the correct way ?


(Joe) #5

In the code above you pass the $src_filename as array to the CUploadedFile.




$uploadedFile = CUploadedFile::getInstanceByName('Good');

if(!empty($uploadedFile))

  $uploadedFile->saveAs(...).



Of course you can use basic php to handle the fileupload, but the CUploadedFile will do the move_uploaded_file for you by saveAs …


(Ildar5) #6

thanks that works for me