如何使用Yii2上传文件类接收带图像的POST请求

时间:2014-11-25 13:52:27

标签: rest yii upload

我试图使用" UploadFile"上传一个使用POST请求发送的文件(来自移动设备的exapmle),但我无法做到,我按照官方指南的Yii2.0指南的UploadFile教程但不是很好的结果。

这是我的控制器:forntend \ controllers \ Upload

namespace forntend\controllers;

use Yii;
use yii\web\Controller;
use frontend\models\UploadForm;
use yii\web\UploadedFile;

    class UploadController extends Controller
    {
      public function actionUpload()
      {
        $model = new UploadForm();
         if (Yii::$app->request->isPost) {
                $model->file = UploadedFile::getInstance($model, 'file');    
                if ($model->validate()) {                
                    $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
                }
      }

    return $this->render('upload', ['model' => $model]);
        }
    } 

这是我的模型:/ frontend / model / UploadForm

命名空间app \ models;

use yii\base\Model;
use yii\web\UploadedFile;

/**
 * UploadForm is the model behind the upload form.
 */
class UploadForm extends Model
{
    /**
     * @var UploadedFile|Null file attribute
     */
    public $file;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['file'], 'file'],
        ];
    }
}

当我发送i POST请求到... localhost / mysite / upload / upload?

时,这不应该工作

感谢您的帮助!!!!!

1 个答案:

答案 0 :(得分:2)