我正在用 flutter 创建一个待办事项列表应用程序,我希望我的用户能够在谷歌驱动器上备份他们的任务。
这是我正在使用的代码:
// Create the file we want to upload.
ga.File fileToUpload = ga.File();
var file = await _localFile;
fileToUpload.parents = ["appDataFolder"];
fileToUpload.name = path.basename(file.absolute.path);
// Create a new back-up file on google drive.
var response = await drive.files.create(
fileToUpload,
uploadMedia: ga.Media(file.openRead(), file.lengthSync()),
);
// Get the file id.
fileId = response.id;
问题是每次我得到不同的文件 id 并且我需要检索文件
从谷歌驱动器始终具有相同的文件ID,而不是每次都具有不同的ID。
我尝试使用 update 方法而不是 create 方法:
ga.File fileToUpload = ga.File();
var file = await _localFile;
fileToUpload.parents = ["appDataFolder"];
fileToUpload.name = path.basename(file.absolute.path);
drive.files.update(fileToUpload, fileId);
但我得到未处理的异常:DetailedApiRequestError(状态:403,消息:父字段在更新请求中不可直接写入。请改用 addParents 和 removeParents 参数。)
我还尝试在使用 create 方法之前设置文件 ID:
fileToUpload.id = fileId;
await drive.files.create(
fileToUpload,
uploadMedia: ga.Media(file.openRead(), file.lengthSync()),
);
但后来我得到未处理的异常:DetailedApiRequestError(状态:400,消息:提供的文件 ID 不可用。)
或者具有该 id 的文件已经存在。
所以我试图从谷歌驱动器中删除该文件,然后使用相同的 ID 再次创建它:
fileToUpload.id = fileId;
drive.files.get(fileId).then((value) {
if (value != null) {
drive.files.delete(fileId).then((value) {
drive.files.create(
fileToUpload,
uploadMedia: ga.Media(file.openRead(), file.lengthSync()),
);
});
} else {
drive.files.create(
fileToUpload,
uploadMedia: ga.Media(file.openRead(), file.lengthSync()),
);
}
});
但后来我也得到未处理的异常:DetailedApiRequestError(状态:400,消息:提供的文件 ID 不可用。)
即使我使用谷歌驱动器为原始文件提供的相同文件ID。
有什么解决办法吗?
最佳答案
您需要首先通过名称检查文件是否存在于驱动器中。由于没有直接的 API 可以从 google 驱动器中获取具有名称的文件,因此您需要使用 List api
并在检查文件名之前先获取文件
为此,您可以使用以下查询
{
q: `'appDataFolder' in parents and trashed = false`
}
收到回复后,您可以检查您的文件是否按名称存在。如果它得到它的 id 并触发
update call
为文件。注意:你不通过
parents
上传 key ,但 addParents
对于媒体上传,您将使用以下网址
PATCH https://www.googleapis.com/upload/drive/v3/files/fileId
如果你没有找到文件,你去创建一个新的方法
// Create the file we want to upload.
ga.File fileToUpload = ga.File();
var file = await _localFile;
fileToUpload.parents = ["appDataFolder"];
fileToUpload.name = path.basename(file.absolute.path);
// Create a new back-up file on google drive.
var response = await drive.files.create(
fileToUpload,
uploadMedia: ga.Media(file.openRead(), file.lengthSync()),
);
关于flutter - 在谷歌驱动器上备份我的本地数据库总是会创建一个不同的文件 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61982139/