PHP强制下载到网页
我有一个强制下载文件的问题。
我正在使用PHPExcel根据从我们的数据库中提取的信息创build一个xls文件。 这一切工作正常,Excel文件根据需要工作。
然后我尝试使用以下function强制下载创build的文件。 但是它下载的网页,而不是一个文件。
目前正在Win XP SP3,Notepad ++,XAMPP(Apache 2.4.3,PHP 5.4.7)上开发。
**function如下
public function downloadfile($file){ if(file_exists($file) && is_file($file)){ //ob_start(); echo $file; echo "in file exists"; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); //ob_end_flush(); }else echo "file or location does not exist <br>"; echo $file; }
任何帮助,将不胜感激。 提前致谢
如果它的一个Excel文件,然后只是redirect到该url,默认情况下,它会要求文件下载。
header("Location: http://site.com/path/to/file/filename.xlsx"); /* Make sure that code below does not get executed when we redirect. */ exit;
如果在JavaScript给
location.href = 'http://site.com/path/to/file/filename.xlsx';
header("Content-Type: application/vnd.ms-excel; charset=UTF-8"); header("Content-Disposition: inline; filename=\"" . $fileName . ".xls\""); header("Pragma: no-cache"); header("Expires: 0"); readfile($filePath);
尝试这个