Flutter Web如何实现Google Drive文件直接下载及部署异常解决
Flutter Web文件下载问题解决方案
问题1:本地资源部署到GitHub Pages后下载为.html文件
Debug模式下本地资源路径能正常解析,但部署到GitHub Pages后,受静态文件路由规则影响,直接用相对路径会被导向站点404页面(返回404.html),导致下载错误文件。
解决方法
通过Uri.base.resolve()把相对资源路径转换成部署后的绝对URL,确保锚点指向正确的文件:
import 'dart:html' as html; Future<void> downloadLocalResume() async { // 生成部署后的资源绝对URL final String resumeUrl = Uri.base.resolve("assets/docs/resume.pdf").toString(); html.AnchorElement anchorElement = html.AnchorElement(href: resumeUrl); anchorElement.download = "resume.pdf"; // 明确文件后缀,保证浏览器识别格式 anchorElement.click(); } // 对应修改TextButton的点击事件 TextButton( onPressed: downloadLocalResume, child: FittedBox( child: Row( children: [ Text( "Download CV", style: TextStyle( color: Theme.of(context).textTheme.bodyText1!.color, ), ), const SizedBox(width: defaultPadding / 2), SvgPicture.asset("assets/icons/download.svg") ], ), ), ),
问题2:Google Drive文件无法直接下载,仅跳转预览
Google Drive默认共享链接为预览模式,需修改链接参数触发直接下载行为。
解决方法
调整链接格式:把共享链接中的
/view?usp=sharing替换为/uc?export=download,示例:- 原链接:
https://drive.google.com/file/d/XXX/view?usp=sharing - 修改后:
https://drive.google.com/file/d/XXX/uc?export=download
- 原链接:
处理大文件确认提示:若文件较大,Google会弹出确认页面,可通过XMLHttpRequest绕开预览,直接获取文件流:
import 'dart:html' as html; Future<void> downloadGDriveFile(String fileId) async { final String url = "https://drive.google.com/uc?export=download&id=$fileId"; final html.XmlHttpRequest request = html.XmlHttpRequest(); request.open('GET', url); request.responseType = 'blob'; request.onLoad.listen((event) { if (request.status == 200) { final html.Blob blob = request.response; final String url = html.Url.createObjectUrlFromBlob(blob); final html.AnchorElement anchor = html.AnchorElement(href: url) ..download = "resume.pdf" ..click(); html.Url.revokeObjectUrl(url); } }); request.send(); } // 使用时传入你的Google Drive文件ID TextButton( onPressed: () => downloadGDriveFile("你的文件ID"), child: FittedBox( child: Row( children: [ Text( "Download CV", style: TextStyle( color: Theme.of(context).textTheme.bodyText1!.color, ), ), const SizedBox(width: defaultPadding / 2), SvgPicture.asset("assets/icons/download.svg") ], ), ), ),
注意事项
- 确保Google Drive文件设置为公开可下载(共享权限设为“知道链接的任何人都可查看/下载”)
- 小文件直接修改链接参数即可,大文件建议用XMLHttpRequest方法避免跳转确认页面
内容的提问来源于stack exchange,提问作者Shanmukha
相关产品推荐
相关产品推荐

