Как загрузить файлы в веб-папку в расширенном шаблоне yii2?
Я пытаюсь загрузить файлы в бэкэнд, и каждый раз, когда я загружал файл, он был успешно загружен и успешно сохранен в БД, но не был сохранен в каталог, который я указал, так что мое приложение не может найти файл, и я уже дал 777 разрешение на загрузку папки в веб-каталоге. ниже мои коды
Модель для обработки и сохранения файла загрузки ...
Как загрузить файлы в корневую папку в расширенном шаблоне yii2?
Модель отвечает за загрузку
<?php
namespace backend\models;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\Validators\FileValidator;
class UploadForm extends Model {
public $img;
public $randomCharacter;
public function rules(){
return[
[['img'], 'file', 'skipOnEmpty' => false, 'extensions'=> 'png, jpg,jpeg'],
];
}
public function upload(){
$path = '/uploads/';
$randomString = '';
$length = 10;
$character = "QWERTYUIOPLKJHGFDSAZXCVBNMlkjhgfdsaqwertpoiuyzxcvbnm1098723456";
$randomString = substr(str_shuffle($character),0,$length);
$this->randomCharacter = $randomString;
if ($this->validate()){
$this->img->saveAs($path .$randomString .'.'.$this->img->extension);
return true;
}else{
return false;
}
}
}
Модель продукта отвечает за сохранение информации в базе данных
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\Validators\FileValidator;
class Products extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'products';
}
public function rules()
{
return [
[['name'], 'string', 'max' => 100],
[['descr', 'img', 'reviews'], 'string', 'max' => 255],
// [['file'], 'file', 'skipOnEmpty' => false, 'extensions'=> 'png, jpg,jpeg']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'img' => 'Img',
];
}
}
my controller and the action
public function actionCreate()
{
$time = time();
$model = new Products();
$upload = new UploadForm();
if ($model->load(Yii::$app->request->post()) ) {
//get instance of the uploaded file
$model->img = UploadedFile::getInstance($model, 'img');
//define the file path
$upload->upload();
//save the path in the db
$model->img = 'uploads/' .$upload->randomCharacter .'.'.$model->img->extension;
$model->addtime = $time;
$model->save();
return $this->redirect(['view', 'product_id' => $model->product_id]);
}else {
return $this->render('create', [
'model' => $model,
]);
}
}
and my view file has been modified too thanks for any help