2017-10-14 80 views
0

我想通過react-images-upload包上傳圖像。但是,我不知道API處理應該是什麼樣子。ReactJS上傳圖像與yii2 api

迄今陣營代碼:

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,'image')填充$模型時,它在var_dump-ing之後仍然是空的。

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

因爲你不是使用ActiveForm$model生成表單,和你的形式沒有具體的名稱使用

$model->image = \yii\web\UploadedFile::getInstanceByName('image'); 

    //instead of 
    $model->image = UploadedFile::getInstance($model, 'image'); 
0

,你必須獲得文件嘗試:

$model->image = UploadedFile::getInstanceByName('image'); 
+0

當的var_dump在$ model->圖片中,它只顯示NULL。我認爲這與請求有關。 –