为什么下载的图片打不开?

Why can't downloaded image be opened?

我在 Wordpress 中使用 ACF 并用它创建了一个图片库。每张图片都应有一个下载 link,以便在单击时将图片下载到用户计算机。但是,当我尝试下载时,它显示下载,但随后无法打开图像。相反,我收到一条错误消息,指出图像无法打开并且可能已损坏或使用了无法识别的文件格式(图像下载为 jpg)。 这是我创建的下载link。

 <a href="<?php get_stylesheet_directory().'/webservices/download.php?filename='.$media_gallery_image['image_download_link']; ?>"
                           title="click to download this image"
                           target="_blank"
                           class="js-download"
                           download="<?php echo $media_gallery_image['image_download_link']; ?>"><?php echo $translated[$lang]['download_text']; ?></a>

这是我的 download.php 文件。

<?php

$file = $_GET['file'];

download_file($文件);

函数 download_file( $fullPath ){

// Must be fresh start
if( headers_sent() )
    die('Headers Sent');

// Required for some browsers
if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');

// File Exists?
if( file_exists($fullPath) ){
    // Parse Info / Get Extension
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);

    // Determine Content Type
    switch ($ext) {
        case "gif": $ctype="image/gif"; break;
        case "png": $ctype="image/png"; break;
        case "jpeg":
        case "jpg": $ctype="image/jpg"; break;
        default: $ctype="application/force-download";
    }

    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false); // required for certain browsers
    header("Content-Type: $ctype");
    header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".$fsize);
    ob_clean();
    flush();
    readfile( $fullPath );

} else
    die('File Not Found');

}

我不明白为什么这不起作用。有人可以告诉我我做错了什么吗?提前谢谢你。

看来我想把它复杂化了...终于成功了。任何其他试图解决这个问题的人,这对我有用。这是我的 download.php 文件。

    <?php
if ( $_SERVER['REQUEST_METHOD'] === 'GET' ) {
    if ( !is_null( $_GET['filename'] ) && !empty( $_GET['filename'] ) ) {
        $file = $_GET['filename'];
        $fname = basename( $file );
        try {
            header( 'Content-type: image/*' );
            header( "Content-Disposition: attachment; filename=\"$fname\"" );
            readfile( $file );
        } catch ( Exception $ex ) {
            echo $ex->getMessage();
        }
    }
}