代码之家  ›  专栏  ›  技术社区  ›  Comp

有没有可能不先在服务器上下载解码文件,然后再在客户端上下载,而直接在客户端pc上下载?

php
  •  0
  • Comp  · 技术社区  · 7 年前

    所以我正在使用gmailapi。为了得到附件,我得到了必须用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 回复  |  直到 7 年前
        1
  •  1
  •   deceze    7 年前

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