首页 > 解决方案 > 是否可以不在服务器上然后在客户端上下载解码文件,而直接在客户端电脑上?

问题描述

所以我正在使用 Gmail API。为了获取附件,我获取了必须使用 base64 解码的数据。但这与问题完全无关。现在我允许用户像这样下载图片/文件:

$attachment = $service->users_messages_attachments->get($userId, $_GET["messageId"], $_GET["attachment_id"]);
$data = $attachment->getData();
$data = strtr($data, array('-' => '+', '_' => '/'));

 $myfile = fopen("picture.jpg", "w+");;
 fwrite($myfile, base64_decode($data));
 fclose($myfile);

echo "<a href= 'picture.jpg' download= 'picture.jpg'>Download</a>";

它工作得很好,但我认为我会使用太多的服务器空间(我将每个图片/文件保存在服务器上,然后允许用户下载它)。我可以将它直接下载到客户端电脑上,而不在服务器上保存图片/文件吗?

标签: php

解决方案


您正在做的是将数据写入文件,然后输出包含指向该文件的链接的 HTML 页面。您可以简单地输出一个指向 PHP 页面的链接,而不是这样做,该页面将输出该文件的数据。

因此,您的链接将如下所示:

<a href='download.php?messageId=42&attachment_id=69' download='picture.jpg'>Download</a>

download.php会做这样的事情:

header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename="picture.jpg"');

$attachment = $service->users_messages_attachments->get($userId, $_GET["messageId"], $_GET["attachment_id"]);
$data = $attachment->getData();
echo strtr($data, array('-' => '+', '_' => '/'));

推荐阅读