How To Upload A File Using A Model in yii? - php

i have read this article http://yiiframework.com/wiki/2
and i have done everything step by step .
but it's not working !
this is the model which i just copy and then paste :
class Item extends CActiveRecord
{
public $image;
// ... other attributes
public function rules()
{
return array(
array('image', 'file', 'types'=>'jpg, gif, png'),
);
}
}
my view is exactly the same as the article :
$form = $this->beginWidget(
'CActiveForm',
array(
'id' => 'upload-form',
'enableAjaxValidation' => false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)
);
// ...
echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image');
echo $form->error($model, 'image');
// ...
echo CHtml::submitButton('Submit');
$this->endWidget();
and my controller is :
class ItemController extends CController
{
public function actionCreate()
{
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
{
$model->image->saveAs(dirname(__FILE__).'/a.txt');
// redirect to success page
}
}
$this->render('create', array('model'=>$model));
}
}
when i choose an image(jpg , png , or something else) the controller doesn't see my file , i mean isset($_FILES['Item']) is false ... i know it's false because i check it with var_dump hundreds of times :
public function actionCreate()
{
$model=new Item;
var_dump(isset($_POST['Item']));
...
i also test var_dump(isset($_FILES['Item'])) which was false either .
for every kinds of file(except plain txt file) $_POST['Item']) remains empty.
i checked my request using firebug network panel(both Firefox and chrome) and the request had the file .
i have already check this question , seems it's the same problem but the answers wasn't useful because CUploadedFile::getInstance and CUploadedFile::getInstanceByName are also return null for my case
what do you think ?

The Problem was not related to Yii Framework or my php code because i just test the same code on two different machine and that works just fine .
i am using wamp on my own computer and i guess the problem was something related to Apache or php configurations.

In controller change and use like this:
class ItemController extends CController
{
public function actionCreate()
{
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
$uploadedFile = CUploadedFile::getInstance($model,'image');
if($model->save())
{
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
if($model->image == null || empty($model->image)){
$rnd = rand(0,9999);// generate random number between 0-9999
$fileName = "{$rnd}-{$uploadedFile}";
$model->image = $fileName;
}
$uploadedFile->saveAs(dirname(__FILE__)..'/images/'. $model->image);
// redirect to success page
}
}
}
$this->render('create', array('model'=>$model));
}
}

Related

FileUpload to upload image fail to save the image, but no error message displayed

I'm using Yii2 basic. It doesn't seems like anything's wrong, no error message displayed, but why did my image didn't upload? The rest (title, content etc) get uploaded through the form,though
This is my model's rule and related method:
public $image;
public function init(){
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/uploads/batam/';
Yii::$app->params['uploadUrl'] = Yii::$app->urlManager->baseUrl . '/uploads/batam/';
}
public function rules()
{
return [
[['title', 'content'], 'required'],
[['content'], 'string'],
[['created_at', 'updated_at','image'], 'safe'],
[['image'], 'file','extensions'=>'jpg,png,jpeg'],
[['title'], 'string', 'max' => 255],
];
}
public function getImageFile()
{
return isset($this->image) ? Yii::$app->params['uploadPath'].$this->image : null;
}
public function uploadImage() {
$image = UploadedFile::getInstance($this, 'image');
if (empty($image)) {
return false;
}
$this->image = $image->name;
return $image;
}
This is my controller
public function actionCreate()
{
$model = new News();
if ($model->load(Yii::$app->request->post()) )
{
// process uploaded image file instance
$image = $model->uploadImage();
if($model->validate())
{
if($model->save())
{
// upload only if valid uploaded file instance found
if ($image !== false)
{
$path = $model->getImageFile();
$image->saveAs($path);
}
return $this->redirect(['view', 'id'=>$model->id]);
}
}
else{echo " validation is failed";}
}
else{
return $this->render('create', [
'model' => $model,
]);
}
}
This is the form
echo $form->field($model, 'image')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],
'pluginOptions' => [['previewFileType' => 'any']]
]);
I had included the enctype also at the beginning of the form
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
At this point inside the if ($image !== false) part of the controller , the $image and $path to be saved-as contains a seemingly correct path.
This is my $path : C:\xampp\htdocs\gbia/uploads/batam/test image 1-01.jpg and my $image also contain the object (not null). This is the var_dump of my $image :
object(yii\web\UploadedFile)#179 (5) { ["name"]=> string(19) "test image 1-01.jpg" ["tempName"]=> string(24) "C:\xampp\tmp\php3199.tmp" ["type"]=> string(10) "image/jpeg" ["size"]=> int(925184) ["error"]=> int(0) }
I think something wrong with the saveAs(), but I can't figure it out. Had googled around, look on stackoverflow and tutorials but I still can't find any answer. Can someone help? Thanks
Check your model, you have declared $image as a public variable of the class, and not as a field in the database, if you want to store the data there, it will never work, as the public property that is temporary will have preference over the database column.
public $image;
So delete this field (If it is also in the db) or generate a new column name (I suggest by the name of path).
[['content', 'path'], 'string'],
Then you need to store the path, I don't see where are you doing that in the controller or class. I suggest you to add a field in the database with the "path" name and then do like this in the controller:
$path = $model->getImageFile();
$image->saveAs($path);
$model->path = $path . $image // You must store the full path plus the file name
$model->save(); // then you save the model again
Any doubt is welcome, I have example projects that I can show you if you are unable to see the light.

How to parse csv file uploaded via file and show the content in result view in Zend

I am using Zend 1.12
I have a form which has two fields: email, and file
My index view shows the form. And after validation is successful, I want to parse the csv file and show the content on result view:
My Code:
IndexController:
class IndexController extends Zend_Controller_Action {
public function init() {
/* Initialize action controller here */
}
public function indexAction() {
// action body
$form = new Application_Form_FileUpload();
$form->submit->setLabel('Upload');
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$file = $form->getValue('file');
$email = $form->getValue('email');
//$this->_helper->viewRenderer('result', null, true);
//$this->_helper->redirector('result', 'index','', array('email' => $email, 'file' => $file));
$this->_helper->redirector->gotoRouteAndExit (array(
'controller' => 'index',
'action' =>'result',
'name' => $file));
} else {
$form->populate($formData);
}
}
}
public function resultAction() {
$email = $this->_getParam('name');
$this->view->email = $email;
}
}
My index view:
<?php
$this->form->setAction($this->url(array('action' => 'index')));
echo $this->form;
?>
My result view:
<?php
echo $this->email;
//echo the content of the csv file;
?>
My result view is empty always.
What is the correct/right way to get the form data, and if validation is successful, show the content in result view.
Edit: I have succeeded to get parameters passed to resultaction.
I just was looking into different file. That is why it was not showing up.
But still, is it the right way to do it for my case? For it seems not correct.

how to upload file to mysql table using path in yii

I try to upload a file to MySQL table and it does not work.
here what i write:
view:
<div class="row">
<?php echo $form->labelEx($model,'doc_ordered_recieved'); ?>
<?php echo $form->fileField($model,'doc_ordered_recieved'); ?>
<?php echo $form->error($model,'doc_ordered_recieved'); ?>
</div>
model:
i add this attribute:
public $doc_ordered_recieved;
and this rulse:
array('doc_ordered_recieved','file','types'=>'pdf', 'allowEmpty'=>true, 'on'=>'update'),
controllers:
public function actionCreate()
{
$model=new Orders;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Orders']))
{
$model->attributes=$_POST['Orders'];
$model->doc_ordered_recieved=CUploadedFile::getInstance($model,'doc_ordered_recieved');
if($model->save())
{
$doc_ordered_recieved->saveAs('http://localhost/files');
$this->redirect(array('view','id'=>$model->oid));
}
}
$this->render('create',array('model'=>$model,
));
}
please help me i don't know why its not work????
thanks you all
eliya
First you need to change the rule to add create scenario:
array('doc_ordered_recieved','file','types'=>'pdf', 'allowEmpty'=>true, 'on'=>'insert,update'),
and in your create action from your controller you need to do this:
public function actionCreate()
{
$model=new Orders;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Orders']))
{
$model->attributes=$_POST['Orders'];
$uploadedFile = CUploadedFile::getInstance($model,'doc_ordered_recieved');
if($model->save())
{
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
if($model->image == null || empty($model->image)){
$rnd = rand(0,9999);// generate random number between 0-9999
$fileName = "{$rnd}-{$uploadedFile}";
$model->image = $fileName;
}
$uploadedFile->saveAs(dirname(__FILE__)..'/files/'. $model->doc_ordered_recieved);
// redirect to success page
}
$this->redirect(array('view','id'=>$model->oid));
}
}
$this->render('create',array('model'=>$model,
));
}
Just by looking at your code I can see that you need to change your file path from
$doc_ordered_recieved->saveAs('http://localhost/files');
to
$doc_ordered_recieved->saveAs(Yii::app()->basePath.'path/to/localFile');
Also, you should provide more information about your model.

uploading images in Yii, error $model->save()

Im trying to upload images and add to db file name and now Im stuck, because it wont add entry to db.
Error in debugger is Property "EeCarTypes.foto" is not defined.
controllers relavent code:
public function actionCreate()
{
$model=new EeCarTypes;
$path = Yii::app()->basePath . '/../images/upload/cartypes';
if (!is_dir($path)) {
mkdir($path);
}
if(isset($_POST['EeCarTypes']))
{
$model->attributes=$_POST['EeCarTypes'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
{
$model->image->saveAs( $path . '/adsfasdfadf' );
}
}
$this->render('create', array('model'=>$model));
}
view code:
$form = $this->beginWidget(
'CActiveForm',
array(
'id' => 'upload-form',
'enableAjaxValidation' => false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)
);
// ...
echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image');
echo $form->error($model, 'image');
// ...
echo CHtml::submitButton('Submit');
$this->endWidget();
and model code:
public $image;
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'ee_car_types';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array( 'image', 'file', 'types' => 'jpg, gif, png'),
array('car_type', 'length', 'max'=>255),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, car_type', 'safe', 'on'=>'search'),
);
}
I think anything else is irelevent here. Please help me :)
**Replace your view code**
echo $form->fileField($model, 'image');
with
<?php echo CHtml::activeFileField($model, 'image'); ?>
**In your controller file**
if(isset($_POST['EeCarTypes']))
{
$rnd = rand(0,9999);
$model->attributes=$_POST['EeCarTypes'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
$fileName = "{$rnd}-{$uploadedFile}";
$model->image = $fileName;
$model->attributes=$_POST['EeCarTypes'];
if($model->save()){
$uploadedFile->saveAs(Yii::app()->basePath.'/../images/upload/cartypes'.$fileName);
$this->redirect(array('index'));
}
}
At your model you should create a name property for the image and the field at the database. Then assign the file name to this property at your action method before you call the save(), like this:
$file = CUploadedFile::getInstance($model,'image');
$model->image_name = $file->name;
//use this if you want to save the file type but first create the image_type property
$model->image_type = $file->type;
[...]
Create an attribute with the name foto in your model EeCarTypes and look here

Yii automatic generate report when data has been saved

How do I get when it finishes inserting the data, perform direct application automatically generates reports based on the data that has just inputted ?
My controller (Save) :
public function actionCreate()
{
$model=new PurchaseOrder;
if(isset($_POST['PurchaseOrder']))
{
$model->attributes=$_POST['PurchaseOrder'];
if($model->save())
$this->redirect('index');
}
$this->render('create',array(
'model'=>$model,
));
}
My controller (Generate Report) :
public function actionCetak()
{
if(isset($_POST['PrintPO'])){
$data = $_POST['no_po'];
if($data==''){
return false;
}else{
$HTML2PDF = Yii::app()->ePdf->HTML2PDF();
$HTML2PDF->WriteHTML($this->renderPartial('data_print', array(
'data' => $this->loadCetak($data)
), true));
$HTML2PDF->Output();
}
}else{
$this->render('form_cetak_po');
}
}
both functions run smoothly, but when I combining into :
public function actionCreate()
{
$model=new PurchaseOrder;
if(isset($_POST['PurchaseOrder']))
{
$model->attributes=$_POST['PurchaseOrder'];
if($model->save())
$HTML2PDF = Yii::app()->ePdf->HTML2PDF();
$HTML2PDF->WriteHTML($this->renderPartial('data_print', array(
'data' => $this->loadCetak($model->id)
), true));
$HTML2PDF->Output();
$this->redirect('index');
}
$this->render('create',array(
'model'=>$model,
));
}
Application only do the insert function. How do I order when finished doing the insert, directly akang application and the data it generates can be downloaded.
Thanks
You misses brackets after if(save())
Look at this :
if(isset($_POST['PurchaseOrder']))
{
$model->attributes=$_POST['PurchaseOrder'];
if($model->save())
{ // <-- add this
$HTML2PDF = Yii::app()->ePdf->HTML2PDF();
$HTML2PDF->WriteHTML($this->renderPartial('data_print', array(
'data' => $this->loadCetak($data)
), true));
$HTML2PDF->Output();
} //<-- add this
else
{
$this->redirect('index');
}
}
Redirecting after download
I don't think this can be done.
The common thing in popular download sites is the reverse: first you go to the "after" page and then the download starts.
You can do this :
after save,redirect to something like this
index.php?r=controller/index&file_info=information
and in index method, check if ($_GET['file_info']), then create your pdf file and make the download.
Look at the top answer here

Categories