创建下载链接PHP

时间:2016-04-11 05:06:55

标签: php image hyperlink download

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

- >的download.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

我的代码有什么问题?

1 个答案:

答案 0 :(得分: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!=图像类型。