简体   繁体   English

xlsx文件在php下载中损坏

[英]xlsx File is corrupted on download in php

I need to download xlsx file in php. 我需要在php中下载xlsx文件。 The file is downloading but when i open it shows as corrupted file. 该文件正在下载,但当我打开时显示为损坏的文件。 I used zend Framework 我用过zend Framework

Controller: 控制器:

$fullPath = '/opt/bitnami/lampstack-5.4.36-0/apps/projects/ProjectName/File_Name.xlsx';

 if ($fd = fopen ($fullPath, "r")) 
 {
   $fsize = filesize($fullPath);
   $path_parts = pathinfo($fullPath);
   $ext = strtolower($path_parts["extension"]);             

   header("Content-type: application/xlsx");
   header("Content-Disposition: attachment;filename=\"".$path_parts["basename"]."\"");
   header("Content-length: $fsize");
   header("Cache-control: private");

   while(!feof($fd)) 
   {
     $buffer = fread($fd, 2048);
     echo $buffer;//To display the file content while downloaded.
    }
   }
   fclose ($fd);

View: 视图:

<?php echo $this->buffer; ?>

Other than xlsx/xls file is downloading correctly(PDF/any image file). xlsx / xls文件以外的文件正在正确下载(PDF /任何图像文件)。

There are multiple problems than can occur and lead to this error. 可能会发生多个问题,并导致此错误。

First thing to do is probably to set header like this : 首先要做的可能是像这样设置标头:

header('Content-Length: ' . filesize('./uploads/resources/courses/' . $filename));

and

header('Content-Transfer-Encoding: binary');

Just to be sure this is neither a header nor a filesire problem. 只是要确保这既不是标题也不是文件问题。

Often with xlsx file you'll have a BOM at the begining of the file. 通常,对于xlsx文件,在文件开头会带有BOM。 There is a very easy way to test out if it is the problem using unzip. 有一种非常简单的方法可以测试是否使用解压缩是问题。 Try to unzip your xlsx file and if you have something like this then this is the BOM causing the problem. 尝试解压缩您的xlsx文件,如果您有类似这样的文件,则这是导致问题的BOM。

unzip -l your-file.xlsx 

You should see 你应该看到

warning file:  3 extra bytes at beginning or within zipfile.

You can also check with the hex viewer 您也可以使用十六进制查看器进行检查

head -c5 your-file.xlsx | xxd -g 1

If you have an output like this : 如果您有这样的输出:

 0000000: ef bb bf 50 4b 

Then it's a BOM problem (notice the 3 first byte ef bb bf ). 这是一个BOM问题(请注意第三个字节ef bb bf )。

Removing the bom (internet is full of solution for this), or encoding the file to UTF-8 should do the trick. 删除bom(Internet可以解决此问题),或将文件编码为UTF-8即可解决问题。

Hope it helped ya. 希望对你有帮助。

I found the problem. 我发现了问题。 I cut and paste the code in separate controller which having downloading code only. 我将代码剪切并粘贴到仅具有下载代码的单独控制器中。 In that time it works. 在那个时候它起作用了。

It is caused because of error occur in init function(Mapping needed controller and model files). 这是由于init函数发生错误(映射所需的控制器和模型文件)引起的。 Comment each file and check and found error in one file. 注释每个文件,然后在一个文件中检查并发现错误。

Hope this answer will help someone 希望这个答案可以帮助某人

Thanks for your comment. 谢谢你的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM