Google Drive API上传同名文件不自动覆盖原因及无ID覆盖方法咨询
原代码无法自动覆盖的原因
Google Drive的文件标识逻辑不依赖「父文件夹+文件名」的组合,所有文件独立使用唯一的file ID作为身份凭证。你本地手动上传时看到的覆盖提示,是Drive前端额外做的同名检查逻辑,原生Drive API的files.create接口本身没有内置该逻辑,每次调用只会直接生成新文件,所以会出现多个同名文件共存的情况。
无需手动指定file ID的自动覆盖实现方案
实现逻辑很简单:上传前先检索目标父文件夹下是否存在同名未删除的文件,存在就调用更新接口覆盖内容,不存在就走原来的新建逻辑。
完整修改后代码
from googleapiclient.http import MediaFileUpload from Google import Create_Service CLIENT_SECRET_FILE = 'client-secret.json' API_NAME = 'drive' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/drive.file'] service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) # 配置参数 file_name = 'image.jpg' local_file_path = 'image.jpg' parent_folder_id = 'insert parents here' mime_type = 'image/jpg' # 检索目标文件夹下的同名未删除文件 search_response = service.files().list( q=f"name='{file_name}' and '{parent_folder_id}' in parents and trashed=false", fields='files(id, name)' ).execute() matched_files = search_response.get('files', []) media_content = MediaFileUpload(local_file_path, mimetype=mime_type) if matched_files: # 存在同名文件,执行更新覆盖 target_file_id = matched_files[0]['id'] file = service.files().update( fileId=target_file_id, media_body=media_content ).execute() else: # 无同名文件,新建上传 file_metadata = { 'name': file_name, 'parents': [parent_folder_id] } file = service.files().create( body=file_metadata, media_body=media_content ).execute() print(file)
注意事项
- 如果目标文件夹下存在多个同名文件,上述代码默认会覆盖第一个检索到的文件,你可以根据业务需求调整匹配规则
- 如果文件名包含单引号,需要先对
q参数里的文件名做单引号转义,避免查询语法报错
内容的提问来源于stack exchange,提问作者Enzo
相关产品推荐
相关产品推荐

