Yii2.0中如何通过POST API上传文件到服务器?

2024-01-04

我通过此链接在 yii2 中制作了一个模型http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html我使用 POST 请求将文件发布到 API,并在控制器中获取了所有文件信息,但无法使用使用上述链接创建的 Yii2.0 模型上传文件,正常的 PHP 文件上传代码工作正常。 这是我的控制器代码

public function actionUploadFile()
    {
        $upload = new UploadForm();
        var_dump($_FILES);

        $upload->imageFile = $_FILES['image']['tmp_name'];
        //$upload->imageFile = $_FILES;
        var_dump($upload->upload());
    }

我的模型代码是

class UploadForm extends Model
    {
    /**
     * @var UploadedFile
     */
    public $imageFile;

    public function rules()
    {
        return [
            [['imageFile'], 'safe'],
            [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
        ];
    }

    public function upload()
    {
        try {
            if ($this->validate()) {
                $this->imageFile->saveAs('/var/www/html/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
                var_dump("Jeree");
                return true;
            } else {
                var_dump($this->getErrors());
                return false;
            }
        }catch (ErrorException $e) {
            var_dump($e->getMessage());
        }
    }
    }

试试这个方法

public function actionUpload()
{
   $model = new UploadForm();

   if (Yii::$app->request->isPost) {
       $model->file = UploadedFile::getInstance($model, 'file');

       if ($model->validate()) {                
          $model->file->saveAs('/var/www/html/' . $model->file->baseName . '.' . $model->file->extension);
       }
    }

    return $this->render('upload', ['model' => $model]);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Yii2.0中如何通过POST API上传文件到服务器? 的相关文章

随机推荐