PHP 文件下载流程

时间:2022-10-25 06:36:38

前台HTML:

添加download属性,不打开download.php页面

<a style='color:blue' href='download.php' download='data/CrawlerID.txt' target=_blank>下载</a>

download.php

1:从数据库中导出内容

2:fread输出到页面

<?php
//下载数据
header('Content-Type:text/html;charset=utf-8');
$crawlId=$_GET['id']; //导出sql语句:Select pid,price Into OutFile 'F:/QQPCmgr/Desktop/Data_OutFile.txt' fields terminated by ',' From `t_product`
//导出文件命名格式Crawl_ID_txt;
$filePath = "D:/WWW/amazon_crawl_system/data/";//此处给出你下载的文件在服务器的什么地方
$fileName = "CrawlerID_".$crawlId.".txt"; //删除文件
if(file_exists($filePath.$fileName)){
unlink($filePath.$fileName);
} include_once('./mysql.php');
$conndb=new ConnDB();
$conndb->connect("127.0.0.1","root","root","amazon"); //首先从t_crawl_url表中获取对应的id值,拼接sql语句
$sql="select id from t_crawl_url where crawl_id=".$crawlId;
$request=$conndb->queryarr($sql);
$str='';
if($request){
foreach($request as $key => $values){
$str.="crawl_url_id='".$values['id']."' or ";
}
$str=substr($str,0,strlen($str)-4);
//echo $str;
}else{
echo "error";
exit;
} $sql="select pid,price Into OutFile '".$filePath.$fileName."' fields terminated by ',' lines terminated by '\r\n' From `t_product` where ".$str; $request=$conndb->query($sql);
if($request){
/*echo "<script> window.location.href='download.php?id=".$crawlId."&file=".$saveFile."';</script>";*/
}else{
echo "<script> alert('下载失败');</script>";
exit;
} //此处给出你下载的文件名
$file = fopen($filePath.$fileName, "r"); //打开文件
//输入文件标签
header("Content-type:application/octet-stream ");
header("Accept-Ranges:bytes ");
header("Accept-Length: " . filesize($filePath.$fileName));
header("Content-Disposition: attachment; filename= ".$fileName); //输出文件内容
echo fread($file, filesize($filePath . $fileName));
fclose($file); ?>