【发布时间】:2020-02-26 22:32:28
【问题描述】:
根据Google Drive API 上的文档,我正在尝试将文件上传到 Google 云端硬盘的根文件夹。我通过 Google 登录对用户进行了身份验证,这不是问题。我不断收到从服务器返回的 411 错误,上面写着
“POST 请求需要
Content-length标头。这就是我们所知道的。”。
我有一个 Content-length 标头,但它似乎不被接受。这是我的代码,
Uri uri = Uri.parse('https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable');
http.MultipartRequest request = new http.MultipartRequest('POST', uri);
request.headers["Authorization"] = header['Authorization'];
request.headers['content-type'] = "application/json; charset=UTF-8";
request.headers['X-Upload-Content-Type'] ='video/mp4';
request.headers['X-Upload-Content-Length'] = lengthInBytes.toString();
request.headers['name'] = fileName;
request.headers['content-length'] = (request.contentLength).toString();
//request.files.add(await http.MultipartFile.fromPath('$fileName', file.path,));
print("request.toString: " + request.toString());
http.StreamedResponse response = await request.send();
print('ok: ' + response.statusCode.toString());
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
我知道的唯一一行是文件名,因为 API 站点上的文档略有不同,我不确定我是否正确编码。这是 Google 网站上的 API 示例,
POST https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable HTTP/1.1
Authorization: Bearer [YOUR_AUTH_TOKEN]
Content-Length: 38
Content-Type: application/json; charset=UTF-8
X-Upload-Content-Type: image/jpeg
X-Upload-Content-Length: 2000000
{
"name": "myObject"
}
我可以对大小约为 5MB 的文件进行分段上传,但我需要能够上传更大的文件,并且可恢复是唯一的选择。如果需要,我可以发布有效的多部分代码。
【问题讨论】:
-
也许尝试不要将
request.headers['content-length'] = (request.contentLength).toString();转换为toString(),因为内容长度必须是整数。让我知道这是否有效。 :)
标签: rest http flutter dart google-drive-api