下载或查看位于服务器 b yii 2 中的上传文件



我已经将文件上传到服务器,我想下载该文件。我应该怎么做.

这是控制器中的上传

{
$model = new Upload();  
if ($model->load(Yii::$app->request->post()))
{
$filename = $model->_upload;
$model->_upload= UploadedFile::getInstance($model,'_upload');
$model->_upload->saveAs('uploads/'.$filename.'.'.$model->_upload->extension);
$model->_upload = 'uploads/'.$filename.'.'.$model->_upload->extension;
$model->save();
return $this->redirect(['view', 'id' => $model->id_uploads]);


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

假设您的uploads文件夹位于 web 目录或 webroot 中,您可以使用以下函数,只需将粘贴复制到控制器中,然后下载文件,在查询字符串中键入 url 以及filename,例如,如果您的控制器名称是FilesController那么 url 将被www.mydomain.com/files/download?filename=your_file_name

/**
* Downloads the file
*
* @param string $filename the name of the file to be downloaded
*
* @return mixed
*/
public function actionDownload($filename)
{
$filepath = Yii::getalias('@webroot') . DIRECTORY_SEPARATOR
. 'uploads' . DIRECTORY_SEPARATOR . $filename;
return Yii::$app->response->sendFile($filepath);
}

注意

  • 这是最简单的方法,您将文件名与表中的路径一起保存,这是错误的,您应该仅保存文件名以及扩展名,例如没有路径的扩展名my_file.doc,然后下载文件只需使用文件 ID 而不是文件名或与文件名一起存储的任何类型的哈希值在表中查找文件名桌子

    public function actionDownload($fileId)
    {
    $filename = Upload::findOne(['id_uploads'=>$fileId]);
    $filepath = Yii::getalias('@webroot') . DIRECTORY_SEPARATOR
    . 'uploads' . DIRECTORY_SEPARATOR . $filename;
    return Yii::$app->response->sendFile($filepath);
    }
    
  • 其次,您应该遵循类属性的命名约定,_upload公共属性看起来很奇怪,因为大多数私有成员变量都带有下划线前缀。 你应该使用一些编码标准,如 phpcs

  • 以及if条件中的 2 个重定向语句是怎么回事

    return $this->redirect(['view', 'id' => $model->id_uploads]);
    return $this->redirect(['index']);
    

    第二个是无法访问的,只需将其删除即可。

最新更新