I'm trying to upload a file through FileUploadUI::widget
in yii2 advanced. But I can't achieve my goal. I don't know what the problem is, but the file doesn't appear in the folder I wish to upload to.
this is my view
<?= FileUploadUI::widget([
'model' => $model,
'attribute' => 'img',
'url' => ['image-upload', 'id' => $model],
'gallery' => false,
'fieldOptions' => [
'accept' => 'image/*'
],
'clientOptions' => [
'maxFileSize' => 2000000
],
// ...
'clientEvents' => [
'fileuploaddone' => 'function(e, data) {
console.log(e);
console.log(data);
}',
'fileuploadfail' => 'function(e, data) {
console.log(e);
console.log(data);
}',
],
]); ?>
this is controller my controller is into backend but I want to upload the file to frontend/web/img/temp
action
public function actionImageUpload()
{
$model = new MyNews();
$imageFile = UploadedFile::getInstance($model, 'img');
$directory = Yii::getAlias('/../frontend/web/img/temp/');
if ($imageFile != null) { //can't saveAs() file into my ../img/temp/ folder
$uid = 'qqqq';
$fileName = $uid . '.' . $imageFile->extension;
$filePath = $directory . $fileName;
if ($imageFile->saveAs($filePath)) {
$path = '/../frontend/web/img/temp/' . $fileName;
//.....
}
}
return '';
}
You should use aliases
defined by Yii like @frontend
@backend
rather than providing the path inside the Yii::getAlias()
, few common like i stated are defined in common/config/bootstrap.php
like
Yii::setAlias ( '@frontend' , dirname ( dirname ( __DIR__ ) ) . '/frontend' );
Yii::setAlias ( '@backend' , dirname ( dirname ( __DIR__ ) ) . '/backend' );
The path you are providing is also wrong because Yii is inside the backend/web/
not at the root of backend
app from where you are trying to upload.
What i would suggest is to define your path inside the common/config/bootstrap.php
like below
Yii::setAlias('@uploadDir',realpath(Yii::getAlias('@frontend').'/web/img/temp/'));
and then change your code to the following
public function actionImageUpload()
{
$model = new MyNews();
$imageFile = UploadedFile::getInstance($model, 'img');
$directory = Yii::getAlias('@uploadDir');
if ($imageFile != null) { //can't saveAs() file into my ../img/temp/ folder
$uid = 'qqqq';
$fileName = $uid . '.' . $imageFile->extension;
$filePath = $directory . $fileName;
if ($imageFile->saveAs($filePath)) {
Yii::$app->session->setFlash('success','The file has been uploaded successfuly');
return $this->redirect('index');
}
}
}