单击下载链接时文件损坏

时间:2011-10-01 16:38:06

标签: php html

我尝试使用php强制图片jpg文件下载,我已经实现了以下代码:

HTML

<a href = "filedownload.php?src=uploads/myimage.jpg&download=true>download this file</a>

download.php

 <?php
ob_start();
 include_once 'functions.php';

if (isset($_GET['download']) && $_GET['download'] == 'true')
  {    

  $src = sanitizeString($_GET['src']);
  header('Content-Description: File Transfer');   
  header('Content-Type: image/jpeg');  
  header('Content-Disposition: attachment; filename='.basename($src));  
  header('Content-Transfer-Encoding: binary');  
  header('Expires: 0');   
  header('Cache-Control: public');  
  header('Pragma: public');

  } 

 ?>

假设图像的完整路径是“www.example.com/smith/topic/uploads/myimage.jpg”,我收到了正确的图像名称,也出现了下载窗口,但图像已损坏大小为1KB,任何人都可以告诉我原因,非常感谢。

3 个答案:

答案 0 :(得分:6)

这里是一个如何使用readfile函数的例子

<?php
$file = 'monkey.gif';

if (file_exists($file)) {
    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, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

答案 1 :(得分:1)

您需要一些实际通过文件发送的代码。参见例如readfilefpassthru

答案 2 :(得分:1)

尝试使用:

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