是否可以不先在服务器上然后在客户端上下载解码文件,而直接在客户端PC上下载?

时间:2018-09-30 09:18:30

标签: php

所以我正在使用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>";

它完全可以正常工作,但是我想我会使用过多的服务器空间(我将每个图片/文件保存在服务器上,然后允许用户下载)。是否可以直接将其下载到客户端PC,而不在服务器上保存图片/文件?

1 个答案:

答案 0 :(得分:1)

您正在做的是将数据写入文件,然后输出包含该文件链接的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('-' => '+', '_' => '/'));