【问题标题】:Uploading file using Google Drive API returns "400: Bad Request"使用 Google Drive API 上传文件返回“400:错误请求”
【发布时间】:2013-06-28 12:02:52
【问题描述】:

我正在尝试使用 Google Drive API 和 Java 将文件上传到 Google Drive。

我要上传的文件是 docx 文件(之前使用 Drive API 导出)。我的问题是,当上传文件名包含瑞典字符(如 åäö)的文件时,Drive API 会引发异常。

上传的代码基本上是这样的:

File file = new File("/path/to/file.docx");
String contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";

File fileToUpload = new File()
            .setTitle("abc")
            .setMimeType(contentType);

FileContent mediaContent = new FileContent(contentType, file);

try {
    Drive.Files.Insert request = client.files().insert(fileToUpload, mediaContent);
    request.execute();
} catch (IOException e) {
    logger.error("Could not restore file");
    throw e;
}

这段代码实际上运行良好。 但是如果我将 setTitle("abc") 更改为 setTitle("abcö") 我会得到这个异常:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
Bad Request

我尝试使用 google-api-services-drive 的 v2-rev82-1.14.2-beta 和 v2-rev82-1.15.0-rc 版本,结果相同。

如果有帮助,我正在使用 OSX(Windows 似乎更经常遇到这类问题)。


编辑: 经过一番实验,我发现如果我排除 FileContent 对象(实际文件内容),并且只创建一个上传元数据的空文件,那么标题中的瑞典字符就可以了。

Drive.Files.Insert request = client.files().insert(fileToUpload);

看来,主要问题毕竟不是标题。如果我能弄清楚如何将文件数据添加到空文件中,我应该完成。


EDIT2:找到解决方案!

添加:request.getMediaHttpUploader().setDirectUploadEnabled(true); 启用直接上传(虽然不确定我之前使用的是什么),显然这使得 Google Drive 不再关心我奇怪的瑞典字符(再次,不知道为什么)。

这是我最终得到的代码(经过简化):

File file = new File("/path/to/file.docx");
String contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";

File fileToUpload = new File()
        .setTitle("abcö")
        .setMimeType(contentType);

FileContent mediaContent = new FileContent(contentType, file);

try {
    Drive.Files.Insert request = client.files().insert(fileToUpload, mediaContent);
    request.getMediaHttpUploader().setDirectUploadEnabled(true);
    request.execute();
} catch (IOException e) {
    logger.error("Could not restore file");
    throw e;
}

现在我只需要添加对大文件的可恢复上传的支持,但这是另一回事。

EDIT3:顺便说一句,here are the docs 让我走上了正轨。

【问题讨论】:

    标签: java google-api google-drive-api google-api-java-client


    【解决方案1】:

    将其编码为 UTF-8,或将 uploadType 更改为“media”。

    【讨论】:

    • 试过 UTF-8,同样的错误。看不到如何更改uploadType。 official docs 并不完全清楚如何使用 Java api 做到这一点。
    • 好的,现在我设法解决了这个问题。在执行之前添加这一行就可以了:request.getMediaHttpUploader().setDirectUploadEnabled(true);我猜这和'将uploadType更改为“媒体”'是一回事吗?
    猜你喜欢
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    相关资源
    最近更新 更多