Rest API中的文件上传yii2

时间:2016-05-12 11:35:30

标签: rest yii2

我的控制器文件在api / v1 / controller /

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);
    }
}

}

当我尝试使用Postman中的访问权限时: 发布http://localhost/myapp/api/v1/profiles

我得到无效参数 - yii \ base \ InvalidParamException

响应内容不得为数组。

问题是什么?帮助将不胜感激!感谢

1 个答案:

答案 0 :(得分:3)

您可以直接在Yii2控制器/操作中使用带有Yii2中的表单数据编码的HTTP POST轻松接收单个/多个上传的文件。

使用此代码:

DATE_OF_MATCH TEAM1   GOALS1 GOALS2 ID_TEAM CITY
------------- ------- ------ ------ ------- --------------------
2014-07-08    GER          7      1 BRA     Belo Horizonte

如果您使用Postman API客户端来测试API的工作方式,您可以将上传端点配置为对多文件上传工作:

Body form-data params for POST data request

注意 $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 } 方括号非常重要! Postman很乐意让您在一个插槽中选择多个文件进行上传,但这不会实际工作。按照屏幕截图中显示的方式进行操作,通过upfile[]机制为Yii2操作提供了一系列文件。这大致相当于标准的PHP UploadedFile超全局变量,但处理起来更容易。

可以在键名后面加上或不加$_FILES方括号上传单个文件。当然,你可以根据自己的惯例命名[]