问题描述:

if($_POST['mode']=="save") {

$root = $_SERVER['DOCUMENT_ROOT'];

$path = "/mcboeking/";

$path = $root.$path;

$file_path = $_POST['path'];

$file = $path.$file_path;

if(!file_exists($file)) {

die('file not found');

} else {

header("Cache-Control: public");

header("Content-Description: File Transfer");

header('Content-Type: application/force-download');

header("Content-Disposition: attachment; filename=\"".basename($file)."\";" );

header("Content-Length: ".filesize($file));

readfile($file);}}

As soon as I download the file and open it I get an error message. When i try to open a .doc file I get the message: file structure is invalid.

And when i try to open a .jpg file: This file can not be opened. It may be corrupt or a file format that Preview does not recognize.

But when I download PDF files, they open without any problem.

Can someone help me?

P.s. i tried different headers including :

header('Content-Type: application/octet-stream');

网友答案:
$fsize = filesize($yourFilePath); 
$allowed_ext = array (

  // archives
  'zip' => 'application/zip',

  // documents
  'pdf' => 'application/pdf',
  'doc' => 'application/msword',
  'xls' => 'application/vnd.ms-excel',
  'ppt' => 'application/vnd.ms-powerpoint',

);
$mtype = mime_content_type($file_path);
if ($mtype == '') {
    $mtype = "application/force-download";
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: $mtype");
header("Content-Disposition: attachment; filename=\"$asfname\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fsize);
//then ur rest code
网友答案:

Your headers have no bearing on the actual content, so the issue is that there is something wrong with the actual content.

Also, you really shouldn't try to force a download by changing the Content-Type header. Leave it what it is supposed to be. Let the client decide what to do with it.

网友答案:

Make sure you don't output anything but the readfile() data: ensure that PHP code begins with <? at the very first symbol of the PHP file, and that there are no symbols after the closing ?> at the end of file, like a space or a newline (or remove the ?> altogether).

网友答案:

Open PHP file in NOTEPAD. Press "Save as" and choose "ASCI" file format. This helped in my case, because file was in UTF8 format and this was the cause.

相关阅读:
Top