【问题标题】:How to download a file uploaded on google cloud storage instead of viewing it?如何下载上传到谷歌云存储上的文件而不是查看它?
【发布时间】:2021-04-04 00:24:38
【问题描述】:

我在谷歌云存储上上传了一个文件并将 URL 发送到一个 ejs 文件,在该文件中我将它的 URL 分配给一个按钮。当我单击按钮时,我想下载文件而不是在浏览器中查看它。我怎样才能使它成为可能?

Ejs 文件代码

<div class="send-btn-container">
    <a
        href="<%= downloadLink %>"
        download
        target="_blank"
        type="application/octet-stream"
    >Download file</a>
</div>

【问题讨论】:

  • 您能找到解决方案吗?

标签: html node.js ejs href


【解决方案1】:

我正在回答这个关于 HTML5 的问题。如果您希望下载文件而不是查看文件,可以将download 属性添加到&lt;a&gt; 标记,如下所示:

<a  href="downloadLink.pdf"
        download="mypdf.pdf" <!-- This will force download the file -->
        target="_blank"
        type="application/octet-stream" </a>

在这种情况下,文件downloadLink.pdf 将被下载为mypdf.pdf,但该属性目前仅在 chromium 浏览器中支持。

【讨论】:

  • 这也行不通。我在 chrome 和 edge 中试过这个
  • 就我而言,它按照developers.google.com/web/updates/2011/08/… 工作。
  • 他们放的例子也不能在我的 chrome 浏览器中运行,它正在显示图像而不是下载它。
【解决方案2】:

截至 2018 年底,如果要下载的资源不是来自同一来源或同一服务器,那么点击该链接将不会触发下载。显然,这种限制是一种安全措施。

我以我的 React 代码为例,向您展示一种从 GCloud 存储下载文件的方法。

    const download = (e) => {
        e.preventDefault();
        // Remote URL for the file to be downloaded
        const url = 'https://storage.googleapis.com/...';
        const filename = "mypdf.pdf";
  
        fetch(url)
          .then((response) => response.blob())
          .then((blob) => {
            const blobURL = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = blobURL;
            a.style.display = 'none';
    
            if (filename && filename.length) a.download = filename;
            document.body.appendChild(a);
            a.click();
          })
          .catch((error) => {
            console.error(error);
          });
      };
    
   <a onClick={(e) => download(e)}>
      Download file
   </a>

改为转换为 blob URL。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2021-10-11
    • 2018-07-15
    相关资源
    最近更新 更多