我正在尝试在Google云端硬盘Appdata文件中存储包含配置信息的json对象。我目前正在 JS 中编写应用程序,该应用程序在客户端上运行。使用Google Drive API,我目前可以在appdata文件夹中检查该文件。 如果找不到配置,如何生成新文件并将其存储在appdata文件夹中?
var request = gapi.client.drive.files.list({
'q': '\'appdata\' in parents'
});
request.execute(function(resp) {
for (i in resp.items) {
if(resp.items[i].title == FILENAME) {
fileId = resp.items[i].id;
readFile(); //Function to read file
return;
}
}
//Create the new file if not found
});
答案 0 :(得分:1)
apgi客户端没有提供将文件上传到google驱动器的方法(它确实提供了用于元数据的方法),但是它们仍然公开API端点。 这是我一直在使用V3 API的示例
function saveFile(file, fileName, callback) {
var file = new Blob([JSON.stringify(file)], {type: 'application/json'});
var metadata = {
'name': fileName, // Filename at Google Drive
'mimeType': 'application/json', // mimeType at Google Drive
'parents': ['appDataFolder'], // Folder ID at Google Drive
};
var accessToken = gapi.auth.getToken().access_token; // Here gapi is used for retrieving the access token.
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'}));
form.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id');
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
console.log(xhr.response.id); // Retrieve uploaded file ID.
callback(xhr.response);
};
xhr.send(form);
}
由于Google驱动器将允许重复的文件名,因为它们在ID中是唯一的,所以我使用类似的方法来检查文件名是否已经存在:
function fileExists(file, fileName){
var request = gapi.client.drive.files.list({
spaces: 'appDataFolder',
fields: 'files(id, name, modifiedTime)'
});
request.execute(function(res){
var exists = res.files.filter(function(f){
return f.name.toLowerCase() === fileName.toLowerCase();
}).length > 0;
if(!exists){
saveFile(file, fileName, function(newFileId){
//Do something with the result
})
}
})
}
答案 1 :(得分:0)
查看有关Storing Application Data的文档:
“应用程序数据文件夹”是一个只能由您的应用程序访问的特殊文件夹。其内容对用户和其他应用程序隐藏。尽管对用户隐藏,但Application Data文件夹存储在用户的Drive上,因此使用用户的Drive storage quota。 Application Data文件夹可用于存储配置文件,保存的游戏数据或用户不应直接与之交互的任何其他类型的文件。
为了能够使用您的Application Data文件夹,请求访问以下范围:
https://www.googleapis.com/auth/drive.appdata
如果您要检查有关如何将文件插入Application Data文件夹(PHP代码)的示例代码:
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'config.json',
'parents' => array('appDataFolder')
));
$content = file_get_contents('files/config.json');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'application/json',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
通过添加appDataFolder
作为文件的父级,将使其写入appFolder。然后实现您自己的upload / cody代码,将文件及其内容插入appFolder。
希望这有帮助