Complete code:
public function downloadFile(){ $M = M($this->tableName); $map['id'] = I('fileId'); $info = $M->where($map)->find(); $filepath = '.'.$info['path']; if( !file_exists($filepath) ){ echo '文件不存在!'; exit; } //$M->where($map)->setInc('download'); $file = fopen($filepath,"r"); // 打开文件 // 输入文件标签 Header("Content-type: application/octet-stream"); Header("Accept-Ranges: bytes"); Header("Accept-Length: ".filesize($filepath)); Header("Content-Disposition: attachment; filename=" . $info['savename']); // 输出文件内容 echo fread($file,filesize($filepath)); fclose($file); exit; }
The above code is the method under thinkphp
$this->tableName is the data table for storing files
Get the database response file based on fileId
Use file_exists to determine whether the file exists. If it does not exist, Then the error message is output
Open the file through fopen
The more Header method handles opening the file, and the file is output through the fread() method.