yii2 image not saved in database and can't move to folder - php

I want to upload the image and i want to save the image name in database and move the image to the folder..
But now i can't save any thing.
After uploading the file and submit the form the following error will be displayed
Error (#2)
An internal server error occurred.
My codes are below
In Views:
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?php echo $form->field($model, 'varImage')->fileInput() ?>
<div class="form-group">
<?php echo Html::submitButton('Add', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
In Models:
class Usertype extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['varImage'], 'safe'],
[['varImage'], 'file', 'extensions'=>'jpg, gif, png'],
];
}
public function attributeLabels()
{
return [
'varImage' => 'Image',
];
}
}
In Controller:
$model = new Usertype();
if ($model->load(Yii::$app->request->post()) )
{
$image = UploadedFile::getInstance($model, 'varImage');
$path = Yii::$app->params['uploadPath'] . $model->varImage;
if($model->save())
{
$image->saveAs($path);
Yii::$app->getSession()->setFlash('error', 'User type inserted successfully');
return Yii::$app->getResponse()->redirect('/yii2/site/usertype');
}
}
I can't know what error in this code
Kindly help me to fix this.
Thanks

I think your view and model code is OK.
Try this. This is your controller code. It has worked for me.
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$image = UploadedFile::getInstance($model, 'varImage');
if(!empty($image)){
$image->saveAs('uploads/' . $image->baseName . '.' . $image->extension);
$model->your_database_field_name = $image->baseName . '.' . $image->extension;
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}

In controller:
$fileupload = UploadedFile::getInstance($model, 'image');
if(!empty($fileupload)){
$fileupload->saveAs('uploads/' . $fileupload->baseName . '.' . $fileupload->extension);
$model->image = $fileupload->baseName . '.' . $fileupload->extension;
$model->save();
}
In views:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'image')->fileInput()->label('Upload Photo') ?>
In models:
['image','safe']

Related

Yii2 upload file not getting uploaded to folder

Hi im trying to upload an image but the image is not getting uploaded to the folder.
and i donĀ“t get any error message is there anyone that have a solution to this i followed the documentation on https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload
Controller
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->imageFile = Uploadedfile::getInstance($model, 'imagefile');
if ($model->upload()) {
return;
}
}
return $this->render('upload', ['model' => $model]);
}
Model
public $imageFile;
public $hight;
public $width;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, gif'],
];
}
public function upload()
{
if ($this->validate()) {
$path = $this->uploadPath() . $this->imageFile->namespace . '.' . $this->imageFile->extension;
$this->imageFile->saveAs($path);
$this->image = $this->imageFile->basename . '.' . $this->imageFile->extension;
return true;
} else {
return false;
}
}
public function uploadPath(){
return 'basic/web/uploads/';
}
View
<div class="col-lg-4">
<h2>Heading</h2>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'imageFile')->fileInput() ?>
<button>Resize</button>
<?php ActiveForm::end() ?>
</div>
I think file was not saved to basic/web/uploads folder, please do according to ex, $this->imageFile->saveAs('uploads/' ...
Also try create folder 'uploads' in web/, after this check permissions to the folder

Yii2 Php-Call to a member function getAttributeLabel() on array

I have 3 views. The create and update view are the same. In the _form.php view file. I have this:
<?php
use yii\bootstrap\ActiveForm;
?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'adr_country_id') ->dropDownList($cities) ?>
<?php ActiveForm::end()?>
In the create and update view:
<?= $this->render('_form', ['model' => $model, cities' => $cities ]); ?>
. I can create new record but cant update it. I got the error in the title. This is my controller for update. What might be the problem here? Thanks in advance
public function actionUpdate($id) {
$model = ArrayHelper::map(AdrCountry::find()->all(),'id','name');
$cities = AdrCity::findOne($id);
if ($cities->load(Yii::$app->request->post()) && $cities->validate())
{
$cities->save();
Yii::$app->session->setFlash('success', ' updated');
return $this->redirect(['index']);
}
return $this->render('update',[
'cities' => $cities,
'model' => $model
]); }
Update you controller's action
public function actionUpdate($id) {
$cities = ArrayHelper::map(AdrCountry::find()->all(),'id','name');
$model = AdrCity::findOne($id);
if ($model->load(Yii::$app->request->post()) && $model->validate())
{
$model->save();
Yii::$app->session->setFlash('success', ' updated');
return $this->redirect(['index']);
}
return $this->render('update',[
'cities' => $cities,
'model' => $model
]); }

Yii2 returns error when uploading file to server. Why?

My view:
<?php
$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
?>
<?= $form->field($model, 'document_file')->fileInput()->label(Yii::t('app', 'Attachment')) ?>
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
My model:
class Documents extends \yii\db\ActiveRecord
{
public $document_file;
public function rules()
{
return [
[['document_file'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, xls'],
];
}
}
My controller:
$model = new Documents();
if($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->document_file = UploadedFile::getInstance($model, 'document_file');
$model->document_file->saveAs('uploads/documents/' . $model->document_file->baseName . '.' . $model->document_file->extension);
} else {
print_r($model->getErrors());
}
return $this->render('new', compact('model'));
This code is supposed to upload file to server. But I get the error from print_r - it says
Array ( [document_file] => Array ( [0] => Upload a file. ) )
What am I doing wrong and how to upload a file to server???
File attributes (document_file in your example) could not be assigned via load(), so the value of the following expression is false:
$model->load(Yii::$app->request->post()) && $model->validate()
That is why you got the print error message. You should use UploadedFile::getInstance() to assign the document_file attribute before validate():
$model = new Documents();
if(Yii::$app->request->isPost) {
$model->document_file = UploadedFile::getInstance($model, 'document_file');
if ($model->validate()) {
$model->document_file->saveAs('uploads/documents/' . $model->document_file->baseName . '.' . $model->document_file->extension);
} else {
print_r($model->getErrors());
}
}
return $this->render('new', compact('model'));

Yii2 uploaded image doesn't display

So I've set a CRUD to upload a file to the server's root, in a folder called 'uploads'.
Now, the file is properly saved in the particular folder and the database entry appears to be alright - but the images don't display in the CRUD's 'index' and 'view' actions. Any thoughts on this one?
Create:
public function actionCreate()
{
$model = new PhotoGalleryCategories();
if ($model->load(Yii::$app->request->post())) {
$model->image = UploadedFile::getInstance($model, 'image');
if (Yii::$app->ImageUploadComponent->upload($model)) {
Yii::$app->session->setFlash('success', 'Image uploaded. Category added.');
return $this->redirect(['view', 'id' => $model->id]);
} else {
Yii::$app->session->setFlash('error', 'Proccess could not be successfully completed.');
return $this->render('create', [
'model' => $model
]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
ImageUploadComponent file:
<?php
namespace app\components;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
class ImageUploadComponent extends Component {
public function upload($model) {
if ($model->image) {
$imageBasePath = dirname(Yii::$app->basePath, 1) . '\uploads\\';
$imageData = 'img' . $model->image->baseName . '.' . $model->image->extension;
$time = time();
$model->image->saveAs($imageBasePath . $time . $imageData);
$model->image = $imageBasePath . $time . $imageData;
if ($model->save(false)) {
return true;
} else {
return false;
}
}
}
}
And the index file for the views:
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\modules\admin\models\PhotoGalleryCategoriesSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Photo Gallery Categories';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="photo-gallery-categories-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Photo Gallery Categories', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'name',
'image' => [
'attribute' => 'image',
'value' => 'image',
'format' => ['image', ['class' => 'col-md-6']]
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
Edit: In the dev tools, I can see the correct source for the image. What's more, I can access it by copy-pasting the address in the browser. (the first rows are images taken from the internet through their address, they are not saved locally.)
if image upload in folder
you check below code in gridview with own path:
[
'attribute' => 'image',
'format' => 'html',
'value' => function($data) {
if (empty($data['image'])) {
$img = 'default.jpg';
} else {
$img = $data['image'];
}
if (file_exists(\Yii::$app->basePath . \Yii::$app->params['path']['product'] . $img)) {
if (file_exists(\Yii::$app->basePath . \Yii::$app->params['path']['product'] . "t-" . $img)) {
$path = \Yii::$app->params['path']['webproduct'] . "t-" . $img;
} else {
$path = \Yii::$app->params['path']['webproduct'] . $img;
}
} else {
if (file_exists(\Yii::$app->basePath . \Yii::$app->params['path']['product'] . "t-default.jpg")) {
$path = \Yii::$app->params['path']['webproduct'] . "t-default.jpg";
} else {
$path = \Yii::$app->params['path']['webproduct'] . "default.jpg";
}
}
return Html::img($path, ['width' => '100px', 'height' => '100px']);
},
],
in params.php
\Yii::$app->params['path']['webproduct']:
'product' => '/web/uploads/product/',
'webproduct' => '/uploads/product/',
notice: i use basic template.
I found this anomaly: while inspecting the image sources, I found out that Yii prepended the baseUrl to the image source, even though it displayed only the correct bit. So I manually assigned the path that goes into the database - this way the images show properly.
This is the upload function after the changes. To test it for the whole backend, I made it a component, and it works flawlessly.
public function upload($model) {
/**
* If the $model->image field is not empty, proceed to uploading.
*/
if ($model->image) {
/**
* Assign current time.
*/
$time = time();
/**
* Create the basePath for the image to be uploaded at #root/uploads.
* Create the image name.
* Create the database model.
*/
$imageBasePath = dirname(Yii::$app->basePath, 1) . '\uploads\\';
$imageData = 'img' . $model->image->baseName . '.' . $model->image->extension;
$imageDatabaseEntryPath = '../../../uploads/';
$modelImageDatabaseEntry = $imageDatabaseEntryPath . $time . $imageData;
$model->image->saveAs($imageBasePath . $time . $imageData);
$model->image = $modelImageDatabaseEntry;
/**
* If the model can be saved into the database, return true; else return false.
* Further handling will be done in the controller.
*/
if ($model->save(false)) {
return true;
} else {
return false;
}
}
}
}

CUploadedFile in yii

my problem is with two or more files.
this codes is form Yii application development cookbook(2nd edition), chapter 4
i use Yii 1.1.14
controller:
<?php
class UploadController extends Controller
{
function actionIndex()
{
$dir = Yii::getPathOfAlias('application.uploads');
$uploaded = false;
$model=new Upload();
if(isset($_POST['Upload']))
{
$model->attributes=$_POST['Upload'];
$files=CUploadedFile::getInstances($model,'file');
if($model->validate()){
foreach($files as $file)
$file->saveAs($dir.'/'.$file->getName());
}
}
$this->render('index', array(
'model' => $model,
'dir' => $dir,
));
}
}
model:
<?php
class Upload extends CFormModel
{
public $file;
public function rules()
{
return [
['file', 'file', 'types'=>'jpg'],
];
}
}
view:
<?php if($uploaded):?>
<p>File was uploaded. Check <?php echo $dir?>.</p>
<?php endif ?>
<?php echo CHtml::beginForm('','post',array('enctype'=>'multipart/form- data'))?>
<?php echo CHtml::error($model, 'file')?>
<?php echo CHtml::activeFileField($model, "[0]file")?>
<?php echo CHtml::activeFileField($model, "[1]file")?>
<?php echo CHtml::submitButton('Upload')?>
<?php echo CHtml::endForm()?>
help me, please
You should fix form enctype, use multipart/form-data instead of multipart/form- data.
You could use CMultiFileUpload
controller:
$images = CUploadedFile::getInstancesByName('image');
foreach ($images as $image => $pic) {
}
view:
$this->widget('CMultiFileUpload', array(
'name' => 'image',
'accept' => 'jpeg|jpg|gif|png',
'duplicate' => 'Duplicate file!',
'denied' => 'Invalid file type',
));
Add to model 'maxFiles' param, if you need validation to work properly for multifiles upload.
public function rules()
{
return array(
array('image', 'file', 'types'=>'jpg,gif,png', 'maxSize'=>'204800', 'allowEmpty'=>true, 'maxFiles'=>4),
);
}

Categories