Yii2 POST 图像在没有 Yii2 命名约定的情况下在 API 中建模
我正在为移动应用程序创建端点以将图像发送到服务器.我正在发布带有 POSTMAN 扩展名的 chrome 图像.图像位于 $_FILES
变量中,并命名为 image
.如何将此图像加载到模型或 UploadedFile
类中?$model->load(Yii::$app->request->post())
行没有正确加载文件,因为它不在 Yii2 的表单命名约定中.
I'm creating an endpoint for a mobile application to send a image to the server. I'm posting the image with the POSTMAN extension for chrome. The image is in the $_FILES
variable, and named image
. How can I load this image into a model, or the UploadedFile
class? The $model->load(Yii::$app->request->post())
line does not correctly load the file, as it is not in Yii2's naming convention for forms.
它目前正在返回:
{
"success": false,
"message": "Required parameter 'image' is not set."
}
代码
models\Image.php
<?php
namespace api\modules\v1\models;
use yii\base\Model;
use yii\web\UploadedFile;
class Image extends Model
{
/**
* @var UploadedFile
*/
public $image;
public function rules()
{
return [
[['image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
$path = dirname(dirname(__FILE__)) . '/temp/';
if ($this->validate()) {
$this->image->saveAs($path . $this->image->baseName . '.' . $this->image->extension);
return true;
} else {
die(var_dump($this->errors));
return false;
}
}
}
controllers\DefaultController.php
<?php
namespace api\modules\v1\controllers;
use api\modules\v1\models\Image;
use yii\web\Controller;
use yii\web\UploadedFile;
use Yii;
class DefaultController extends Controller
{
public $enableCsrfValidation = false;
public function actionIndex()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = new Image();
if (Yii::$app->request->isPost) {
if($model->load(Yii::$app->request->post()))
{
$model->image = UploadedFile::getInstance($model, 'image');
if ($model->upload()) {
// file is uploaded successfully
return ['success' => true, 'message' => 'File saved.'];
}
else return ['success' => false, 'message' => 'Could not save file.'];
}
else return ['success' => false, 'message' => 'Required parameter \'image\' is not set.'];
}
else return ['success' => false, 'message' => 'Not a POST request.'];
}
}
邮递员
您的问题似乎是您用于发送图像文件的名称.通常 Yii2 使用诸如ModelName[attributeName]"之类的表单属性名称,并且您正在发送名为image"的图像文件
Your problem seems to be the name you are using to send the image file. Usually Yii2 uses names for form attributes like "ModelName[attributeName]" and you are sending your image file with the name "image"
有两种方法可以解决这个问题:
There are 2 ways of fixing this:
- 更改用于发送图像文件的名称以遵循相同的命名约定.但是,您似乎并不想要那样.
- 使用
getInstanceByName('image')
方法代替getInstance($model, 'image')
- Change the name you use to send your image file to follow the same naming conveniton. However you don't seem to want that.
- Use
getInstanceByName('image')
method instead ofgetInstance($model, 'image')