使用头部信息下载图片的PHP代码

5

我在PHP和Web编码方面都是初学者。我正在尝试通过PHP提供图像下载。我需要什么额外的代码来实现这一点?我已经尝试过在谷歌上搜索和在这里搜索,虽然我知道这个问题之前已经问过并得到了回答,但是读答案让我这个没有经验的人感到头晕目眩。如果有人能帮助我或指引我正确的方向,我将非常感激!

public function ExportUserImage()
    {
        $image = $this->user->image;

        header("Content-type: image/jpeg");  
        header("Cache-Control: no-store, no-cache");  
        header('Content-Disposition: attachment; filename="avatar.jpg"');
        $outstream = fopen($image,'w'); // Not sure if this is right 
        //>>don't know what I need here<<
        fclose($outstream);

    }

1
echo($image)或者echo($outstream)就可以了。 - KhorneHoly
如果我使用echo($image),那么我是否需要使用outstream / fopen?
  • 同时感谢您的回复
- Alec Gamble
你想下载同一文件夹中的图像avatar.jpg吗?我说得对吗? - Vigneswaran S
不,我只想要使用选择器下载图片,并将其命名为avatar.jpg。 - Alec Gamble
如果 ècho($image) 能够正常工作,那么你就不需要它了。 - KhorneHoly
http://php.net/readfile 这是一个 PHP 函数,用于读取文件并将其发送到输出流。而 $image 是指你的图片路径还是实际的二进制数据呢? - Marc B
1个回答

8

你刚才忘记提供实际的图像流,需要下载。

你可以简单地使用echo $image来输出图片,不需要为此打开一个文件流,因为你已经正确设置了标头(headers)。

public function ExportUserImage()
    {
        $image = $this->user->image;

        header("Content-type: image/jpeg");  
        header("Cache-Control: no-store, no-cache");  
        header('Content-Disposition: attachment; filename="avatar.jpg"');
        echo $image;

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接