Имею проблему валидации файлов при загрузке на сервер. Загружаю картинки.
В общем сразу к делу.
Тип авторизации: Bearer.
Создал табличку Images (хочу дам данные о файлах хранить).
Всё вроде бы стандартно.
Код: Выделить всё
Model:
class Image extends ActiveRecord
{
public $imageFile;
public static function tableName()
{
return '{{%images}}';
}
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created',
'updatedAtAttribute' => 'updated'
],
];
}
public function rules()
{
return [
['imageFile', 'image', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, gif'],
[['filename', 'type', 'path','description'], 'default', 'value' => '']
];
}
}
Код: Выделить всё
Controller:
class ImageController extends ActiveController
{
public $modelClass = 'app\models\Image';
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'items',
];
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors[] = [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
$behaviors[] = [
'class' => HttpBearerAuth::className(),
];
$behaviors['access'] = [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['index', 'create', 'update', 'view'],
'allow' => true,
'roles' => ['participant', 'organizer', 'admin'],
],
[
'actions' => ['index', 'view', 'create', 'update', 'delete', 'options'],
'allow' => true,
'roles' => ['admin'],
],
]
];
return $behaviors;
}
public function actions()
{
$actions = parent::actions();
unset($actions['create']);
return $actions;
}
public function actionCreate()
{
$model = new $this->modelClass;
$modelIds = [];
$model->imageFile = UploadedFile::getInstances($model, 'imageFile');
if ($model->validate()) {
foreach ($model->imageFile as $file) {
if ($file->size) {
$ext = pathinfo($file->name);
$m = new $this->modelClass;
$m->filename = uniqid() . '_' . date_timestamp_get(date_create()) . '.' . $ext['extension'];
$m->type = $file->type;
$m->path = '/images/all/' . uniqid() . '_' . date_timestamp_get(date_create()) . '.' . $ext['extension'];
if ($file->saveAs(\Yii::getAlias('@webroot') . $m->path)) {
$m->save();
$modelIds[] = $m->id;
}
}
}
return new ActiveDataProvider([
'query' => Image::find()->where(['id' => $modelIds])
]);
} else return $model->getErrors();
}
}
Посылаю файлик постом, в ответ имею вот такой ответ вот. Как правильно возвращать Exception из своих rest action я честно говоря так и не понял, если кто объяснит буду премного благодарен, потому для начала просто вернул $model->getErrors() массивчик.
Код: Выделить всё
{
"imageFile": [1]
0: "Please upload a file."
-
}
По форуму курил, но ничего внятного не нашёл если честно, хотелось бы на пальцах если это возможно.
Заранее спасибо!