You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过HTML按钮实现Google Drive存储文件的用户端直接下载

解决Google Drive文件点击按钮跳转编辑页、无法直接下载的方案

核心原因是你使用了Google Sheets的编辑页链接,自然会跳转到在线预览界面,需要换成对应格式的导出链接,再搭配前端/后端逻辑即可实现直接下载。


方案1:前端直接实现(无需后端处理,性能最优)

适合不需要额外权限控制的场景,配置最简单:

  1. 修改Google Sheets链接为导出格式
    将原有格式为https://docs.google.com/spreadsheets/d/[文件ID]/edit?usp=sharing的链接,替换为https://docs.google.com/spreadsheets/d/[文件ID]/export?format=xlsx,把[文件ID]替换为你自己的文件实际ID即可。
  2. 前端按钮绑定导出链接
    两种常用实现代码:
  • 用a标签伪装按钮(最简便)
<a href="https://docs.google.com/spreadsheets/d/替换为你的文件ID/export?format=xlsx" download="file.xlsx">
  <button>点击下载文件</button>
</a>
  • 用form表单实现
<form action="https://docs.google.com/spreadsheets/d/替换为你的文件ID/export?format=xlsx">
  <input type="submit" value="点击下载文件">
</form>

注意:需要提前将Google Drive文件的分享权限设置为「任何知道链接的用户均可查看」,否则其他用户无法下载。


方案2:Flask后端代理下载(适合需要隐藏文件链接、加权限控制的场景)

如果不想暴露Google Drive的原始链接,或者需要给下载加登录校验等逻辑,可以用Flask后端代理文件流返回给用户,代码示例如下:

  1. 先安装依赖:pip install flask gdown
  2. 完整Flask代码:
from flask import Flask, Response
import gdown
from io import BytesIO

app = Flask(__name__)

# 替换为你的Google Sheets文件ID
FILE_ID = "你的文件实际ID"
EXPORT_URL = f"https://docs.google.com/spreadsheets/d/{FILE_ID}/export?format=xlsx"

@app.route("/")
def index():
    return '''
        <html>
        <body>
            <h1>文件下载服务</h1>
            <a href="/download_excel">
                <button>点击下载Excel文件</button>
            </a>
        </body>
        </html>
    '''

@app.route("/download_excel")
def download_excel():
    # 将文件下载到内存,不占用服务器本地存储
    file_mem = BytesIO()
    gdown.download(EXPORT_URL, file_mem, quiet=False)
    file_mem.seek(0) # 重置文件指针到开头
    # 返回文件流触发下载
    return Response(
        file_mem,
        mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        headers={
            "Content-Disposition": "attachment; filename=自定义的下载文件名.xlsx"
        }
    )

if __name__ == "__main__":
    app.run(debug=True)

注意事项

  • 100M以上的大文件不推荐用代理方案,会占用服务器带宽,优先选方案1
  • 两种方案都需要确保Google Drive文件的公开访问权限正常
  • 如果你用的是普通Google Drive文件而非Sheets,导出链接格式改为https://drive.google.com/uc?export=download&id=[文件ID]即可

内容的提问来源于stack exchange,提问作者Lash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:06:04