我想在yii2中将带有图像的数据发布到控制器,但我的错误如下:
这是模型:
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model {
public $imageFile;
public function rules() {
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload($data) {
if ($this->validate()) {
$this->imageFile->saveAs('@frontend/web/traviaAssets/agency/' . md5($data) . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
}
控制器:
$model = new \yii\web\UploadedFile();
if (Yii::$app->request->isPost) {
$model->imageFiles = \yii\web\UploadedFile::getInstance($model, $_FILES['imageFile']);
}else{
return false;
}
在表单中发布名称为imageFile的图像文件,但我有这样的错误:
Unknown Method – yii\base\UnknownMethodException
Calling unknown method: yii\web\UploadedFile::formName()
答案 0 :(得分:0)
UploadedFile getInstance方法应该包含模型和属性。
在控制器中使用此代码:
$model->imageFile = \yii\web\UploadedFile::getInstance($model, 'imageFile');
$model->upload('someData');