2016-05-12 62 views
1

API/V1 /控制器內我的控制器文件/文件上傳yii2

class ProfileController extends ActiveController 
{ 
public $modelClass = 'app\models\Profile'; 

public function behaviors() 
{ 
    return [ 
     [ 
      'class' => 'yii\filters\ContentNegotiator', 
      'only' => 
        ['index', 'view', 'createnew','update','search'], 
      'formats' => 
        ['application/json' => Response::FORMAT_JSON,], 

     ], 
     'verbs' => [ 
      'class' => VerbFilter::className(), 
      'actions' => [ 
       'index' => ['get'],    
       'view' => ['get'],    
       'createnew' => ['post'],  
       'update' => ['put'],   
       'delete' => ['delete'],   
       'deleteall' => ['post'], 
       'search' => ['get'] 
      ], 

     ] 
    ]; 
} 

public function actionCreatenew() { 
    $model = new Profile(); 
    $model->load(Yii::$app->request->post()); 



    $model->asset = UploadedFile::getInstance($model, 'asset'); 

    $name = $model->user_id; 

    if($model->asset) { 

     $model->asset->saveAs('uploads/'.$name.'. 
         '.$model->asset->extension); 
     $model->asset = $model->asset->name.'.'. 
         $model->asset->extension; 

    } 



    if($model->save()) { 
     echo json_encode(array('status'=>"Success", 
       'data'=>$model->attributes),JSON_PRETTY_PRINT); 
    } else { 
     echo json_encode(array('status'=>"Failure", 
       'error_code'=>400, 
       'errors'=>$model->errors),JSON_PRETTY_PRINT); 
    } 
} 

}

當我嘗試使用上網本從郵差一樣: POST http://localhost/myapp/api/v1/profiles

我獲取無效參數 - yii \ base \ InvalidParamException

響應內容不能是數組。

什麼問題?幫助將不勝感激!由於

+0

我通過在我的api/config.php文件中添加了這個問題''urlManager'=> ['enablePrettyUrl'=> true,'enableStrictParsing'=> true,'showScriptName'=> false,'rules' => [['class'=>'yii \ rest \ UrlRule','controller'=> ['v1/country','v1/profile'],'extraPatterns'=> ['POST createnew'=>'createnew ',],],],],' – Jackhad

回答

0

您應該使用\yii\web\UploadedFile::getInstanceByName('asset');代替的getInstance()結帳這個Link

+0

感謝您的支持(如您所述添加)。但我得到「響應內容不能是一個數組。」不是爲了我相信。 – Jackhad

+1

在哪一行?你爲什麼迴應json字符串?你可以簡單的使用 ''return ['status'=>'success','data'=> $ model-> attributes];'' – mohit

+0

指定的行是http://imgur.com/riULw0B – Jackhad

2

可以使用HTTP POST在Yii2 form-data編碼,直接在Yii2控制器/動作容易接收單/多載的文件。

使用此代碼:

$uploads = UploadedFile::getInstancesByName("upfile"); 
    if (empty($uploads)){ 
     return "Must upload at least 1 file in upfile form-data POST"; 
    } 

    // $uploads now contains 1 or more UploadedFile instances 
    $savedfiles = []; 
    foreach ($uploads as $file){ 
     $path = //Generate your save file path here; 
     $file->saveAs($path); //Your uploaded file is saved, you can process it further from here 
    } 

如果使用郵差API客戶端來測試您的API是如何工作的,你可以配置上傳端點喜歡這個工作,多文件上傳:

Body form-data params for POST data request

注意upfile[]方括號非常重要!郵差會愉快地讓你選擇多個文件上傳到一個插槽中,但這不會實際上的工作。按照屏幕截圖所示的方式進行操作,可通過UploadedFile機制,爲Yii2操作提供一系列文件。這大致相當於標準的PHP $_FILES超全局變量,但處理更簡單。

在密鑰名稱之後,可以使用或不使用[]方括號上傳單個文件。當然,無論您喜歡什麼,您都可以爲您的約定命名upfile