使用PHP强制下载图像

使用PHP强制下载图像,php,android,Php,Android,我正在尝试使用php从网站下载一个图像,代码如下 目前,它识别并下载该文件。但是 下载的文件未打开,它显示为已损坏。下面代码中的问题是什么 此外,我将此页面嵌入到我的一个移动应用程序中。它在移动安卓设备上也能工作吗 <?php $file = "http://example.com/animals/1.jpg"; // Parse Info / Get Extension $fsize = filesize($file); $path_parts = pathinf

我正在尝试使用php从网站下载一个图像,代码如下

目前,它识别并下载该文件。但是 下载的文件未打开,它显示为已损坏。下面代码中的问题是什么

此外,我将此页面嵌入到我的一个移动应用程序中。它在移动安卓设备上也能工作吗

<?php
$file = "http://example.com/animals/1.jpg";
    // Parse Info / Get Extension
    $fsize = filesize($file);
    $path_parts = pathinfo($file);
    $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: die('Wrong Extension');
    }

    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=\"Test".basename($file)."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . $fsize);
    ob_clean();
    flush();
    readfile($file);
exit();
?>

您需要将数据流发送到浏览器

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream'); // change this will work for you.
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;

您需要将数据流发送到浏览器

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream'); // change this will work for you.
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;

谢谢你的回复。我尝试使用给定的代码。但它仍然显示同样的东西,即图像已损坏或损坏,或太大,无法打开。我看到一张图片的大小稍微缩小了。原始图像为9kb,但下载的图像为8kb。这是引起问题的原因吗?谢谢你的回复。我尝试使用给定的代码。但它仍然显示同样的东西,即图像已损坏或损坏,或太大,无法打开。我看到一张图片的大小稍微缩小了。原始图像为9kb,但下载的图像为8kb。这是导致问题的原因吗?