使用GDrive Multipart Upload jQuery上传至Google Drive时文件无内容问题求助
解决Google Drive API上传文件无内容的问题
嘿,我明白你现在卡在哪了——能成功创建文件但内容是空的,这问题出在你处理文件二进制内容的方式上,咱们来快速搞定它:
问题根源
你之前的代码直接把importFiles[0](也就是File对象)拼接到了字符串格式的请求体里,JavaScript会自动把这个File对象转换成[object File]这样的文本字符串,而不是文件实际的二进制内容。Google Drive收到的只是这段无效文本,自然生成的文件就没有实际内容啦。
修复后的代码
咱们改用FormData来构建请求体,浏览器会帮我们正确处理multipart请求的各个部分,包括二进制文件内容:
var importFiles = $('#files')[0].files; // 先检查是否选中了文件 if (importFiles.length === 0) { alert('请先选择要上传的文件'); return; } const file = importFiles[0]; // 构建文件元数据 const metadata = { 'name': file.name, 'mimeType': file.type, 'parents': ['parent-id'] // 记得替换成你实际的父文件夹ID }; // 用FormData组装multipart请求 const formData = new FormData(); formData.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' })); formData.append('file', file); // 发送请求 gapi.client.request({ 'path': '/upload/drive/v3/files', 'method': 'POST', 'params': { 'uploadType': 'multipart' }, 'headers': { 'Authorization': 'Bearer ' + gapi.client.getToken().access_token, 'Content-Type': undefined // 让浏览器自动生成正确的multipart边界和Content-Type }, 'body': formData }).then(response => { console.log('文件上传成功!', response.result); }).catch(error => { console.error('上传出错了:', error); });
额外注意事项
- 确认
parent-id是你有权限写入的文件夹ID,不然会返回权限错误 - 确保用户授权的OAuth scope包含
https://www.googleapis.com/auth/drive.file(或者更宽泛的drive权限,不过推荐用最小必要权限) - 如果还是有问题,可以在
catch里打印完整的错误信息,方便排查
内容的提问来源于stack exchange,提问作者Leo Letto
相关产品推荐
相关产品推荐

