doxzrb8721 2016-08-16 19:55
浏览 19
已采纳

每当我尝试使用此PHP脚本除txt文件下载任何内容时获取损坏的文件

Whenever i run this script , i get a corrupted file .Downloading is happening but i get a corrupted file .let it be a zip file ,img file ,only txt files are working good.Plz help

<?php
function download($file){
$file="1.jpg";
$dir = './files/';
$path = $dir.$file;
if(!file_exists($path)){
    die('Error');
}else{
    header('Content-Disposition: attachment; filename='.basename($path));
    header('Content-Type: image/jpeg');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($path));
    readfile($path);

}
}

    download("1.jpg");


?>
  • 写回答

2条回答 默认 最新

  • douxian9943 2016-08-16 21:46
    关注

    If you are desperately trying to force a file download in php, then you can redirect to the url of your file using:

    header("Location: $path");
    

    This method is very frequently used, especially if the file doesn't have a MIME type which is supported by the browser. However, if you do know the MIME type of the file you want to be download, it is strongly recommended that you use the appropriate Content-type header for that purpose.For instance, if you want to force a jpg file download (as in your example) then you will have to use something like this:

    header('Content-Disposition: attachment; filename='.basename($path));
    header('Content-Type: image/jpeg');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($path));
    readfile($path);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计