I am unable to upload files in root folder.
I uploaded files in root folder and access these files in frontend and backend application.
Here is complete solution of image uploading,updating, deleting an image. Please follow the steps carefully.
uploads
folder in your root directory.Open you common/config/bootstrap.php and add this line top of the file
Yii::setAlias('@root', realpath(dirname(__FILE__).'/../../'));
---
public function rules()
{
return [
['image', 'image',
'skipOnEmpty' => true,
'extensions' => 'jpg, gif, png']
];
}
<?php
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'image')->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end() ?>
class PostController extends Controller
{
public function actionCreate()
{
$model = new Post();
if ($model->load(Yii::$app->request->post())) {
$file = \yii\web\UploadedFile::getInstance($model, 'image');
if (!empty($file))
$model->image = $file;
if($model->save())
{
if (!empty($file))
$file->saveAs( Yii::getAlias('@root') .'/uploads/' . $file);
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', ['model' => $model]);
} else {
return $this->render('create', ['model' => $model]);
}
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())){
$file = \yii\web\UploadedFile::getInstance($model, 'image');
if (!empty($file)){
$delete = $model->oldAttributes['image'];
$model->image= $file;
}
else{
$model->image = $model->oldAttributes['image'];
}
if($model->save())
{
if (!empty($file))
$file->saveAs( Yii::getAlias('@root') .'/uploads/' . $file);
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', ['model' => $model]);
} else {
return $this->render('update', ['model' => $model]);
}
}
public function actionDelete($id)
{
$model = $this->findModel($id);
if(file_exists(Yii::getAlias('@root') . '/uploads/'. $model->image))
unlink(Yii::getAlias('@root') . '/uploads/'. $model->image);
$model->delete();
return $this->redirect(['index']);
}
}
[
'attribute' => 'image',
'format' => 'html',
'value' => function ($data) {
return Html::img('../../../uploads/'. $data['image'],
['width' => '70px']);
},
],
[
'attribute'=>'image',
'label'=> 'Post Picture',
'value'=> '../../../uploads/' . $model->image,
'format'=>['image',['width'=>100, 'height'=>100]]
],
if you have hide frontend/web then add this rule in your project root (yii2-app) .htaccess file:
RewriteEngine on
RewriteCond %{REQUEST_URI} /(uploads)
RewriteRule ^uploads/(.*)$ uploads/$1 [L]
<img src="<?php echo 'uploads/'.$model->image; ?>">
When using the advanced template you need to decide on a common place to store your files that can be accessed by both the frontend and backend application, additionally if you want the files to be publicly accessible via the web you need to insure this location is a public folder.
I tend to use the frontend/web folder as my common upload location. When uploading from the backend I write to this location. I can then use the images in the frontend.
Example uploading form the backend.
UploadForm.php
Create a model to manage the upload data, make sure to include the file attribute.
class UploadForm extends Model
{
/**
* @var UploadedFile file attribute
*/
public $file;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['file'], 'file', 'extensions'=>'jpg, gif, png'],
];
}
}
UploadController
In the controller that will be managing the upload use the alias for the frontend to set your upload path $path = Yii::getAlias('@frontend') .'/web/uploads/'
class MediaController extends Controller
{
public function actionIndex()
{
$model = new UploadForm();
//Set the path that the file will be uploaded to
$path = Yii::getAlias('@frontend') .'/web/upload/'
if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->file && $model->validate()) {
$model->file->saveAs($path . $model->file->baseName . '.' . $model->file->extension);
}
}
return $this->renderPartial('index', ['model' => $model]);
}
}
View Form
Add a form to your view, make sure to set the 'multipart/form-data'
enctype so that it can accept file uploads.
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']) ?>
<?= $form->field($model, 'file')->fileInput(); ?>
<?= Html::submitButton('Upload') ?>
<?php ActiveForm::end() ?>
Front End
You can then access the image in the front end via /upload/{image-name}.{extension}. example <img src="/upload/sample.png">
Note: it is a good idea to store your upload path in the common/config/params.php so that you can access from both frontend and backend.