Yii 2. Upload document outside public folder

2019-02-26 13:08发布

I have a requirement to upload a document to server, since it is a personal one, they want it to be uploaded outside public folder. I know how to upload a file:

if ($model->load(Yii::$app->request->post())) {

            $model->document = UploadedFile::getInstance($model, 'document');
            if ($model->upload() !== false) {
                $model->save();
            }

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }

But how do I read it since a Url will not be able to access it? I was planning to create an action to get the file but not sure if Yii has something ready for this case?

1条回答
相关推荐>>
2楼-- · 2019-02-26 13:26

Yes Yii can send file output, but you still have to create your own action.

Lets assume following code in siteController Specific to image output, You can use same way to output other files.

public function actionImage($image_path) {
      Yii::$app->getResponse()->sendFile(Yii::getAlias('@image_uploads') . $image_path);
}

now image src will be something like

<img src="/site/image?image_path=/posts/1.png" /> or equivalent to the real application url routes

So basic function to send file output by Yii2 is

Yii::$app->getResponse()->sendFile();

Located Under

\yii\web\Response.php

查看更多
登录 后发表回答