【问题标题】:Create Download Link PHP创建下载链接 PHP
【发布时间】:2016-08-01 02:46:00
【问题描述】:

我的代码有问题。当我点击按钮下载图片时,出现了我不知道的代码,如何解决?我的代码有什么问题?

--> 下载.php

if (isset($_GET['file']) && basename($_GET['file']) == $_GET['file']) {
    $filename = $_GET['file'];
} else {
    $filename = NULL;
}


// define error message
$err = '<p style="color:#990000">Sorry, the file you are requesting is unavailable.</p>';

if (!$filename) {
    // if variable $filename is NULL or false display the message
    echo $err;
} else {
    // define the path to your download folder plus assign the file name
    $path = '../images/upload/lowongan_pekerjaan/'.$filename;
    // check that file exists and is readable
    if (file_exists($path) && is_readable($path)) {
        // get the file size and send the http headers
        $size = filesize($path);
        header('Content-Type: application/octet-stream');
        header('Content-Length: '.$size);
        header('Content-Disposition: attachment; filename='.$filename);
        header('Content-Transfer-Encoding: binary');
        // open the file in binary read-only mode
        // display the error message if file can't be opened
        $file = @fopen($path, 'rb');
        if ($file) {
            // stream the file and exit the script when complete
            fpassthru($file);
            exit;
        } else {
            echo $err;
        }
    } else {
        echo $err;
    }
}

为什么要这样显示? My Picture

我的代码有什么问题?

【问题讨论】:

  • 您可以在图像编辑器中打开文件并重新保存吗?我之前遇到过图像损坏的问题。
  • 还要检查您包含的任何 php 文件末尾的任何空格。空行可能会导致下载出现问题。由于空白行计入您指定的长度,因此它永远不会下载完整图像
  • 当我更改为@thomas-b 时仍然存在同样的问题,这是我的 bursa_detail.php,它具有用于访问 download.php 下载海报
  • 你已经开始输出模板了吗? @alfiyan28。如果要让它下载图像,则不能输出 html 或其他任何内容。图像输出必须是您回显的唯一内容
  • 大家好,我已经成功下载了上面代码的图片。但是现在的问题是,当图像已在打开时下载时,它会显示“Windows 照片查看器无法打开此图片,因为文件似乎已损坏或太大”

标签: php image hyperlink download


【解决方案1】:
    header('Content-Type: application/octet-stream');
    header('Content-Length: '.$size);
    header('Content-Disposition: attachment; filename='.$filename);
    header('Content-Transfer-Encoding: binary');

应该是

    header('Content-Type: image/jpg');
    header('Content-Length: '.$size);
    header('Content-Disposition: attachment; filename='.$filename);

或 png 或 gif 或任何您的文件类型。浏览器不知道如何处理您发送的内容,因为 application/octet-stream != 图像类型。

【讨论】:

  • 我猜他正试图让它作为文件下载弹出,因此是八位字节流内容类型。这迫使人们点击保存文件或打开而不是直接在浏览器窗口中打开
  • Content-Disposition: 附件应该可以做到这一点。但是我只是使用他的代码进行了测试,并且可以正常工作。所以我的猜测是从 $_GET['filename']
  • [[FIXED]] 在 header('Content-Transfer-Encoding: binary') 之后添加 ob_flush();谢谢大家
猜你喜欢
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-27
  • 2012-05-24
  • 1970-01-01
相关资源
最近更新 更多