PHP downloading excel file becomes corrupt

瘦欲@ 提交于 2019-12-05 19:37:03

try doing it this way

 ob_get_clean();
 echo file_get_contents($filename);
 ob_end_flush();
Brad Christie

For one, only specify Content-Type once. You can use the excel-specific header but the generic application/octet-stream may be a safer bet just to get it working (the real difference will be what the browser shows the user with regards to "what would you like to open this file with", but basic browsers can rely on the extension as well)

Also, make sure you specify Content-Length and dump the size (in bytes) of the file you're outputting. The browser needs to know how big the file is and how much content it's expecting to receive (so it doesn't stop in the middle or a hiccup doesn't interrupt the file download).

So, the entire file should consist of:

<?php
  $filename = '/var/www/web1/web/public/temporary/Spreadsheet.xls';

  header("Content-Disposition: attachment; filename=ExcelFile.xls;");
  header('Content-Type: application/octet-stream');
  header('Content-Length: ' . filesize($filename));
  header("Pragma: no-cache");
  header("Expires: 0");

  @readfile($filename);
$file_name = "file.xlsx";

// first, get MIME information from the file
$finfo = finfo_open(FILEINFO_MIME_TYPE); 
$mime =  finfo_file($finfo, $file_name);
finfo_close($finfo);

// send header information to browser
header('Content-Type: '.$mime);
header('Content-Disposition: attachment;  filename="download_file_name.xlsx"');
header('Content-Length: ' . filesize($file_name));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

//stream file
ob_get_clean();
echo file_get_contents($file_name);
ob_end_flush();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!