/ yii2

yii2-upload

文件上传 - Yii2 中文文档

上传文件

class BoardController extends Controller
{
    public function actionCreate()
    {
        $model = new Board();
        $uploadForm = new UploadForm();

        if ($model->load(Yii::$app->request->post()) && $uploadForm->load(Yii::$app->request->post())) {
            // 先处理上传的图片
            $uploadForm->imageFile = UploadedFile::getInstance($uploadForm, 'imageFile');
            // 保存相对地址
            $model->picture = $uploadForm->upload();
            if ($model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

        // 载入数据库中定义的默认值
        $model->loadDefaultValues();

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

上传的文件如何显示

在配置文件 param 中添加一个配置:

return [
    'upload_host' => 'http://upload.example.com/',
];

这样数据表存的是相对路径,日后如何需要迁移到 cdn 只需要将 upload 文件夹复制后,更改配置项即可。

server {
    listen 80;
    listen 443 ssl http2;
    server_name upload.example.com;
    root "/var/www/example.com/uploads";
}

显示上传图片的时候,只需要在 Model 中定义一个 getter 在相对路径前补足域名即可:

class Customer extends ActiveRecord
{
    // ...
    
    // 获取上传图片的 url
    public function getPictureUrl()
    {
        return $this->picture ? Yii::$app->params['upload_host'] . $this->picture : '';
    }

    public function getBirthdayText()
    {
        return date('Y/m/d', $this->birthday);
    }
    
    public function setBirthdayText($value)
    {
        $this->birthday = strtotime($value);
    }
}