流程
- 获取要下载的文件路径,若为网络文件在php处理时需转为本地路径
- php处理,判断是否为文件,或者防注入等处理参数
- 设置header,执行下载
页面
html
<div>
<h2>DOWNLOAD</h2>
<ul>
<li v-for="(value,key) in dirfiles" :key="key">
<a :href="'download.php?path='+value" target="_blank">{{value}}</a>
</li>
</ul>
</div>
vue3
javascript
let dirfiles = ref(null);
function getfiles(){
const url ="getfiles.php";
axios.get(url).then(res=>{
dirfiles.value = res.data.data
}) .catch(error => {
console.error('获取文件失败', error);
});
}
php处理
php
//getfiles.php
include_once "common.php";
$dir = PATH_UPLOAD;
function opendors($dir, $filelist = []) {
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
// 过滤掉当前目录和上一级目录
if ($file != "." && $file != "..") {
$path = $dir . "/" . $file;
if (is_dir($path)) {
$filelist = opendors($path, $filelist);
} elseif (is_file($path)) {
array_push($filelist, $path);
}
}
}
closedir($handle);
}
return $filelist;
}
$filelist = opendors($dir);
backjson(1, "获取成功", $filelist);
php
//download.php
$params = $_GET;
var_dump($params);
$path = $params['path'];
if (!is_file($path)) {
backjson(1, "文件不存在");
}
$fileinfo = pathinfo($path);
var_dump($fileinfo);
$filename = $fileinfo['basename'];
$filesize = filesize($path);
//设置表头
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $filename);
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $filesize);
readfile($path);
exit;