I make a model in yii2 from this link http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html I post the file using POST request to API and got all file information in my controller but unable to upload file using this Yii2.0 model created using above link normal PHP file upload code work fine. Here is my controller code
public function actionUploadFile()
{
$upload = new UploadForm();
var_dump($_FILES);
$upload->imageFile = $_FILES['image']['tmp_name'];
//$upload->imageFile = $_FILES;
var_dump($upload->upload());
}
and my model code is
class UploadForm extends Model
{
/**
* @var UploadedFile
*/
public $imageFile;
public function rules()
{
return [
[['imageFile'], 'safe'],
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
try {
if ($this->validate()) {
$this->imageFile->saveAs('/var/www/html/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
var_dump("Jeree");
return true;
} else {
var_dump($this->getErrors());
return false;
}
}catch (ErrorException $e) {
var_dump($e->getMessage());
}
}
}
Try this way
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->validate()) {
$model->file->saveAs('/var/www/html/' . $model->file->baseName . '.' . $model->file->extension);
}
}
return $this->render('upload', ['model' => $model]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With