I am unable to upload files in root folder.
I uploaded files in root folder and access these files in frontend and backend application.
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.
['enctype' => 'multipart/form-data']) ?>
= $form->field($model, 'file')->fileInput(); ?>
= Html::submitButton('Upload') ?>
Front End
You can then access the image in the front end via /upload/{image-name}.{extension}. example
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.