Yii 2. Upload document outside public folder

左心房为你撑大大i 提交于 2019-12-02 04:28:50

问题


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:


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



来源:https://stackoverflow.com/questions/38105185/yii-2-upload-document-outside-public-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!