我试图通过react-images-upload包上传图片。但是,我不知道API处理应该是什么样子。
到目前为止的React代码:
renderForm() {
return (
<section className="col-md-12 col-sm-12">
<div className="col-md-6 col-sm-6">
<form onSubmit={ this.handleSubmit }>
<div className="form-group">
<ImageUploader
name='image'
withIcon={ true }
buttonText='Choose images'
onChange={ this.onDrop }
imgExtension={ ['.jpg', '.png'] }
maxFileSize={ 1048576 }
withPreview={ true }
label='Max file size: 10mb, accepted: jpg, png'
fileSizeError='File is too big.'
fileTypeError=': not supported extension.'
/>
</div>
<input className="btn btn-default" type="submit" value="Submit" />
</form>
</div>
</section>
);
}
handleSubmit(event) {
event.preventDefault();
this.props.createSponsor(this.state);
}
onDrop(picture) {
this.setState({
pictures: this.state.pictures.concat(picture)
});
}
constructor(props) {
super(props);
this.state = {
name: '',
pictures: []
};
this.handleSubmit = this.handleSubmit.bind(this);
this.onDrop = this.onDrop.bind(this);
}
和Yii2 API代码。当我试图用UploadedFile :: getInstance($ model,&#39; image&#39;)填充$模型时,它在var_dumping之后仍然是空的。
public function actionCreateSponsor()
{
$request = Yii::$app->request;
if ($request->post()) {
$model = new Sponsors();
$model->name = $request->post('name');
$model->image = UploadedFile::getInstance($model, 'image');
//var_dump($model); die;
if (ImageUploadComponent::upload($model)) {
return Json::encode(['status' => true, 'data' => 'success']);
} else {
return Json::encode(['status' => false, 'data' => 'error_not_saved']);
}
}
注意:ImageUploadComponent现在是空的。
答案 0 :(得分:0)
尝试使用
$model->image = \yii\web\UploadedFile::getInstanceByName('image');
//instead of
$model->image = UploadedFile::getInstance($model, 'image');
答案 1 :(得分:0)
由于您没有使用ActiveForm
和$model
来生成表单,并且您的表单没有特定名称,您必须通过以下方式获取文件:
$model->image = UploadedFile::getInstanceByName('image');