2015-10-14 15 views
5

私はこのリンクからyii2でモデルを作成します http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html APIへのPOST要求を使用してファイルを投稿し、コントローラ内のすべてのファイル情報を取得しましたが、上記のリンクを使用して作成したこのYii2.0モデルを使用してファイルをアップロードできません。コードは正常に動作します。 は、ここに私のコントローラのコードYii2.0のPOST API経由でサーバーにファイルをアップロードするには?

public function actionUploadFile() 
    { 
     $upload = new UploadForm(); 
     var_dump($_FILES); 

     $upload->imageFile = $_FILES['image']['tmp_name']; 
     //$upload->imageFile = $_FILES; 
     var_dump($upload->upload()); 
    } 

で、私のモデルコードは

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()); 
     } 
    } 
    } 
+0

は、あなたのモデルを示し、この方法を試してみている、とあなたがいずれかを持っている場合、コントローラは – scaisEdge

+0

は、私が質問を変更してくださいそれを克服する方法を教えてください –

+0

私は経験ではありませんが、$ _filesではなく$ _postを使用する理由は何ですか? '/ var/wwww/html /'は相対パスではなく絶対パスです... 'wwww' 4w?は正しい? – scaisEdge

答えて

3

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]); 
} 
関連する問題