我有一个网站,人们会来这里填写表格,然后他们会收到下载数据集文件的链接,每个文件都有650 MB。我不想使用硬编码路径,否则我的表格将毫无用处,人们将开始通过硬链接下载这些文件。
我不知道如何生成具有这样的能力的动态随机链接文件,以提供650MB大小的文件。
这是一项高级任务,但并非不可能。首先,从创建包含字段的数据库表开始:id、file_path、hash、active-之后为该表创建活动记录模型。
在控制器中创建需要$hash作为参数的下载操作,并在其中放入以下逻辑:
<?php
public function actionDownload($hash)
{
$model = FileModel::find()->where(['hash' => $hash])->one();
if ($model && $model->active == 1) {
$file = $model->file_path;
$model->active = 0;
$model->save(false);
return $this->render('download', ['file' => $file]);
}
return $this->render('downloadLinkExpired');
}
下载视图:
<?php
if (file_exists($file)) {
Yii::$app->response->sendFile($file);
}
然后,在您的表单控制器中,根据当前时间和一些表单字段生成md5哈希(只是为了避免重复的哈希)。对于每个链接,将新模型保存在数据库中。最后,使用hash参数呈现链接。
Url::toRoute('file/download', ['hash'=>$hash])