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

获取Google Drive文件信息触发HttpError 404问题排查

问题诊断与解决方案

核心问题分析

从报错日志看,files().get()调用返回404错误,说明传入的文件ID无效或API无法访问该文件。结合你的代码对比,主要问题出在文件ID提取逻辑不严谨,其次需要排查API权限范围和文件访问权限。

具体修复步骤

1. 修复文件ID提取逻辑

你的代码里定义了extract_drive_file_id但未实际调用,且split('id=')[-1]无法适配所有Google Drive URL格式(比如https://drive.google.com/d/file/d/xxx/view),也会被URL后的额外参数(如&usp=sharing)干扰。改用正则表达式提取更可靠:

import re

def extract_drive_file_id(file_url):
    # 适配所有常见的Drive URL格式
    patterns = [
        r'id=([a-zA-Z0-9_-]+)',
        r'/d/([a-zA-Z0-9_-]+)/',
        r'/file/d/([a-zA-Z0-9_-]+)/'
    ]
    for pattern in patterns:
        match = re.search(pattern, file_url)
        if match:
            return match.group(1)
    return None

2. 完善核心下载逻辑

替换原有的文件ID提取方式,添加异常处理,同时使用系统临时目录避免写入权限问题:

import os
import io
import tempfile
from googleapiclient.errors import HttpError
from flask import jsonify, request as flask_request

@app.route('/download_from_drive', methods=['POST'])
def download_from_drive():
    data = flask_request.get_json()
    url = data.get('url')
    
    if not url:
        return jsonify({'error': '缺少URL参数'}), 400

    # 使用修复后的ID提取函数
    file_id = extract_drive_file_id(url)
    if not file_id:
        return jsonify({'error': '无效的Google Drive链接'}), 400

    try:
        # 获取文件元数据
        file_info = drive_service.files().get(fileId=file_id).execute()
        file_name = file_info['name']

        # 用系统临时目录存储文件,避免权限问题
        temp_dir = tempfile.gettempdir()
        file_path = os.path.join(temp_dir, file_name)

        # 下载文件内容
        with open(file_path, 'wb'):
            print("文件已下载至:", file_path)
            request = drive_service.files().get_media(fileId=file_id)
            fh = io.FileIO(file_path, 'wb')
            downloader = MediaIoBaseDownload(fh, request)
            done = False
            while not done:
                status, done = downloader.next_chunk()
                print("下载进度: %d%%" % int(status.progress() * 100))

        return jsonify({'message': '下载完成', 'file_path': file_path})
    except HttpError as e:
        error_msg = e.error_details[0]['message'] if e.error_details else '未知错误'
        return jsonify({'error': f'Drive API错误: {e.status_code}', 'message': error_msg}), e.status_code
    except Exception as e:
        return jsonify({'error': f'意外错误: {str(e)}'}), 500

3. 排查API权限范围

确保你的OAuth2授权范围包含以下任意一个:

  • https://www.googleapis.com/auth/drive.readonly(只读访问,足够获取元数据和下载文件)
  • https://www.googleapis.com/auth/drive.file(仅访问通过你的应用创建或授权的文件)

如果之前生成的token.json使用了更窄的范围,删除旧token后重新授权即可。

关键原因总结

  1. 文件ID提取不严谨:原逻辑无法适配多格式Drive链接,若URL带额外参数会直接导致无效ID,触发404。
  2. 缺少异常处理:未捕获API错误,导致返回500页面而非JSON错误信息,前端解析失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 07:08:15