如何使用Google Drive API解决文件上传时文件名与父文件夹ID不生效问题
Google Drive API Multipart上传问题修复方案
存在的错误点
- 元数据解析失败:你在metadata的HTTP头和JSON内容之间没有留空行,同时
parents字段格式错误,不需要嵌套对象,直接传入文件夹ID字符串数组即可 - 请求头配置缺失:你注释了必填的
Content-Type头,且头中的boundary值不需要加前置--,只有请求体中的边界标识需要加--前缀 - 协议类型错误:Google Drive的multipart上传要求使用
multipart/related类型,而非你之前写的form-data格式配置
修正后代码
String boundary = 'not_so_random_boundary'; // 构造请求体,注意各部分之间的空行、边界格式 String body = '--' + boundary + '\n' + 'Content-Type: application/json; charset=utf-8\n' + '\n' + // 这里必须加空行分隔头和元数据内容 '{"name":"test.txt","mimeType":"text/plain","parents":["1pf0OL6YqwzE4nClKDcvQAMhe_rYKGs3o"]}' + '\n--' + boundary + '\n' + 'Content-Type: text/plain\n' + '\n' + // 空行分隔头和文件内容 'The file data' + '\n--' + boundary + '--'; Http http = new Http(); HttpRequest req1 = new HttpRequest(); req1.setEndpoint('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart'); req1.setHeader('Authorization', 'Bearer ' + accesstoken); // 正确配置Content-Type头,boundary不需要加-- req1.setHeader('Content-Type', 'multipart/related; boundary=' + boundary); req1.setBody(body); req1.setMethod('POST'); HttpResponse resp1 = http.send(req1); System.debug(resp1.getBody());
修复后即可正常识别自定义文件名,同时文件会存入你指定ID的父文件夹中。
内容的提问来源于stack exchange,提问作者Darshana
相关产品推荐
相关产品推荐

