2017-10-14 2 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 - $ 모델 -> 이미지, 그것은 단지 NULL을 보여줍니다. 나는 그것이 요청과 관련이 있다고 생각한다. –

관련 문제