【发布时间】:2020-03-16 07:00:24
【问题描述】:
我在使用 Google Drive Api v3 下载 Excel .xlsx 文件时遇到了问题。我使用的代码如下(我使用的是the .NET SDK):
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace DriveQuickstart
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-dotnet-quickstart.json
static string[] Scopes = { DriveService.Scope.Drive };
static string ApplicationName = "Drive API .NET Quickstart";
const string FileId = "my_file_id"; //put the ID of the Excel file you want to download here
public static void Main(string[] args)
{
Run().GetAwaiter().GetResult();
Console.Read();
}
private static async Task Run()
{
UserCredential credential;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.GetRequest getRequest = service.Files.Get(FileId);
using (var stream = new System.IO.FileStream("anExcelFile.xlsx", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
{
var downloadProgress = await getRequest.DownloadAsync(stream, CancellationToken.None);
if (downloadProgress.Exception != null)
{
Console.WriteLine(string.Format("We got error {0} {1} {2}", downloadProgress.Exception.Message, Environment.NewLine, downloadProgress.Exception.StackTrace));
}
else
{
Console.WriteLine("Download ok");
}
}
}
}
}
您可以按照here 中描述的步骤轻松运行此示例。这工作正常,但是,只要有人使用 Google 表格打开文件并对其进行修改,我就会开始看到以下错误
D2020-03-16 02:10:13.647293 Response[00000007] Response status: InternalServerError 'Internal Server Error'
D2020-03-16 02:10:13.653278 Response[00000007] An abnormal response wasn't handled. Status code is InternalServerError
D2020-03-16 02:10:13.660288 Response[00000007] Abnormal response is being returned. Status Code is InternalServerError
E2020-03-16 02:10:13.667240 Exception occurred while downloading media The service drive has thrown an exception: Google.GoogleApiException: Internal Server Error
at Google.Apis.Download.MediaDownloader.<DownloadCoreAsync>d__31.MoveNext()
查看使用 Google 表格打开后的文件信息,我可以看到它的大小已更改为 0,因此我尝试将其导出为您对 Google 电子表格的操作,如下所示:
FilesResource.ExportRequest exportRequest = client.Files.Export(fileId, mimeType);
using (var stream = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
{
await exportRequest.DownloadAsync(stream, cancellationToken);
}
使用 mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
但是,然后我运行以下错误:
D2020-03-16 01:53:13.512928 Response[00000003] Response status: Forbidden 'Forbidden'
D2020-03-16 01:53:13.520906 Response[00000003] An abnormal response wasn't handled. Status code is Forbidden
D2020-03-16 01:53:13.525911 Response[00000003] Abnormal response is being returned. Status Code is Forbidden
E2020-03-16 01:53:13.538857 Exception occurred while downloading media The service drive has thrown an exception: Google.GoogleApiException: Google.Apis.Requests.RequestError
Export only supports Google Docs. [403]
Errors [
Message[Export only supports Google Docs.] Location[ - ] Reason[fileNotExportable] Domain[global]
]
at Google.Apis.Download.MediaDownloader.<DownloadCoreAsync>d__31.MoveNext()
因此,在这种特殊情况下,下载和导出似乎都不起作用。还有什么我应该尝试的吗?使用 webContentLink (https://drive.google.com/uc?id=fileId&export=download) 可以正常工作(在浏览器中),所以我想应该可以下载文件。
【问题讨论】:
-
我也遇到了同样的问题,如果你能解决,请告诉我解决方案!
-
嗨@AntoineChaussin!在查看和复制您的代码后,我不清楚这种行为是来自代码本身还是来自 API。为防止遗漏任何重要细节,您能否分享重现此问题的最小完整代码?请在发布之前隐藏或删除脚本上的任何私人身份信息。最后,我也很想知道您是否在只有一个或多个 Google 用户登录的浏览器中测试了这个主题,您能向我澄清一下吗?
-
@Jacques-GuzelHeron,你能看看我的代码吗?下面的代码有效,但仅适用于本机 Google 表格文件:
var request = service.Files.Export(fileId, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); downloadProgress = request.DownloadWithStatus(stream);以下代码有效,直到使用 Google 表格打开和编辑文件。虽然,我几乎 100% 它在 2 周前工作var request = service.Files.Get(fileId); downloadProgress = request.DownloadWithStatus(stream); -
你好@Jacques-GuzelHeron !我已经编辑了这篇文章以获得一个可执行的示例。要重现,请在 Google 驱动器上上传一个 Excel 文件(您可以运行示例然后确认它是否按预期工作),然后使用 Google 表格打开文件,修改它,关闭 GSheet 选项卡,然后再次运行示例。你会得到一个错误。另请注意,这可以在 OAuth 操场上重现,所以我怀疑 .NET 代码是这里的问题。
-
你好@AntoineChaussin 和@JoãoTeixeira!我使用发布的代码来重现错误并遵循您的每一个步骤,但我无法得到相同的错误。我可以毫无问题地下载并打开编辑后的 .XLSX。每个 .XLSX 都会出现这种情况吗?如果没有,请分享一个触发错误的电子表格,以便我重现它。