使用Google.Apis.Drive.v3.DriveService上传文件到Google Drive失败求助
问题原因及修复方案
1. MemoryStream指针位置未重置
调用workbook.SaveAs(stream)后,流的当前位置会停在末尾,后续读取时只能拿到0长度的空内容,触发Google Drive API 400错误,必须取消注释stream.Position = 0,放在SaveAs操作之后、读取流之前。
2. 本地文件写入逻辑被注释
你当前已经注释了将MemoryStream内容写入本地filePath的代码,直接打开的filePath要么不存在、要么是无效的历史文件,读取后也会上传无效内容。可以直接取消本地存盘步骤,把MemoryStream直接传给上传方法,减少冗余操作。
3. MIME类型配置错误
你上传的源文件是标准Excel格式,源MIME类型应为application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,当前配置的application/vnd.google-apps.spreadsheet是谷歌表格专属类型,作为源文件类型会导致API解析失败。如果需要上传后自动转成谷歌表格,仅需要在目标文件配置里指定该类型即可,源类型保持Excel的标准MIME。
4. 缺少结果校验逻辑
你没有判断上传结果的状态,也没有校验Get_Folder_Id_For返回的文件夹ID是否有效,文件夹ID为空或无权限时也会触发400错误。
修复后核心代码示例
// 调用生成和上传逻辑 using (var stream = new MemoryStream()) { Generate_Excel_File(customerReports, stream); // 重置流指针到开头 stream.Position = 0; await Upload_To_Google_Drive(stream, reportName, startDate, endDate); } // 修复后的上传方法核心逻辑 private async Task Upload_To_Google_Drive(Stream stream, string fileName, string startDate, string endDate) { try { _logger.LogInformation($"Uploading {fileName} to Google Drive"); var service = Get_Service(); var folderName = $"Bizvoip : {startDate} to {endDate}"; var folderId = Get_Folder_Id_For(folderName, service); // 新增文件夹ID校验 if (string.IsNullOrEmpty(folderId)) { _logger.LogError($"未找到对应文件夹:{folderName}"); throw new ArgumentException(nameof(folderId)); } // 源文件为标准Excel格式,目标转谷歌表格 var sourceMimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; var targetMimeType = "application/vnd.google-apps.spreadsheet"; var driveFile = new Google.Apis.Drive.v3.Data.File { Name = fileName, MimeType = targetMimeType, Parents = new string[] { folderId } }; // 第三个参数传源文件MIME类型,不要按需请求字段避免不必要的报错 var request = service.Files.Create(driveFile, stream, sourceMimeType); request.Fields = "id,name"; var results = await request.UploadAsync(); // 新增上传结果校验 if (results.Status == UploadStatus.Failed) { _logger.LogError($"上传失败:{results.Exception?.Message}"); throw results.Exception; } } catch (Exception ex) { _logger.LogError("Failed to upload to Google Drive: " + ex.Message); throw; } }
内容的提问来源于stack exchange,提问作者Pierre van der Westhuizen
相关产品推荐
相关产品推荐

