我试图在Google文件中存储一个包含配置信息的json对象。我目前正在用JS编写应用程序,该应用程序运行在客户端上。使用Google,我目前可以检查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
});发布于 2019-05-03 09:11:47
gapi客户端没有提供将文件上传到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
})
}
})
}发布于 2017-04-05 05:34:33
查看有关存储应用程序数据的文档
“应用程序数据文件夹”是一个只有应用程序才能访问的特殊文件夹。它的内容对用户和其他应用程序都是隐藏的。尽管对用户隐藏,但应用程序数据文件夹存储在用户的驱动器上,因此使用用户的驱动器存储配额。“应用程序数据”文件夹可用于存储配置文件、保存的游戏数据或用户不应直接与之交互的任何其他类型的文件。
注意:
若要能够使用应用程序数据文件夹,请请求对以下范围的访问: https://www.googleapis.com/auth/drive.appdata
如果要检查示例代码,说明如何将文件插入应用程序数据文件夹(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。然后实现自己的上载/cody代码,将文件及其内容插入到appFolder。
希望这能有所帮助
https://stackoverflow.com/questions/43173090
复制相似问题