קל לארגן דפים בעזרת אוספים
אפשר לשמור ולסווג תוכן על סמך ההעדפות שלך.
תיקיית נתוני האפליקציה היא תיקייה מוסתרת מיוחדת שבה האפליקציה יכולה לאחסן נתונים ספציפיים לאפליקציה, כמו קובצי תצורה. התיקייה של נתוני האפליקציה נוצרת באופן אוטומטי כשמנסים ליצור בה קובץ.
בתיקייה הזו שומרים קבצים שהמשתמש לא אמור לבצע איתם אינטראקציה ישירה. רק לאפליקציה שלכם יש גישה לתיקייה הזו, והתוכן שלה מוסתר מהמשתמש ומאפליקציות אחרות של Drive.
אי אפשר להעביר קבצים ב-appDataFolder בין מיקומי אחסון (מרחבים). למידע נוסף, ראו ארגון קבצים.
התיקייה של נתוני האפליקציה נמחקת כשמשתמש מסיר את האפליקציה מ-MyDrive. המשתמשים יכולים גם למחוק את תיקיית הנתונים של האפליקציה באופן ידני.
היקף התיקייה של נתוני האפליקציה
כדי לגשת לתיקיית נתוני האפליקציה, צריך לבקש גישה להיקף https://www.googleapis.com/auth/drive.appdata. למידע נוסף על ההיקפים ועל האופן שבו מבקשים גישה אליהם, אפשר לעיין במידע על הרשאה ואימות ספציפיים ל-API. למידע נוסף על היקפי הרשאות ספציפיים של OAuth 2.0, ראו היקפי הרשאות של OAuth 2.0 ל-Google APIs.
יצירת קובץ בתיקיית נתוני האפליקציה
כדי ליצור קובץ בתיקיית נתוני האפליקציה, מציינים את הערך appDataFolder בנכס parents של הקובץ ומשתמשים ב-method files.create כדי להעלות את הקובץ לתיקייה. בדוגמת הקוד הבאה מוסבר איך להוסיף קובץ לתיקייה באמצעות ספריית לקוח.
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.FileContent;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.drive.Drive;importcom.google.api.services.drive.DriveScopes;importcom.google.api.services.drive.model.File;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.util.Arrays;importjava.util.Collections;/** * Class to demonstrate use-case of create file in the application data folder. */publicclassUploadAppData{/** * Creates a file in the application data folder. * * @return Created file's Id. */publicstaticStringuploadAppData()throwsIOException{/*Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application.*/GoogleCredentialscredentials=null;try{credentials=GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA));}catch(IOExceptione){e.printStackTrace();}HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Build a new authorized API client service.Driveservice=newDrive.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Drive samples").build();try{// File's metadata.FilefileMetadata=newFile();fileMetadata.setName("config.json");fileMetadata.setParents(Collections.singletonList("appDataFolder"));java.io.FilefilePath=newjava.io.File("files/config.json");FileContentmediaContent=newFileContent("application/json",filePath);Filefile=service.files().create(fileMetadata,mediaContent).setFields("id").execute();System.out.println("File ID: "+file.getId());returnfile.getId();}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelySystem.err.println("Unable to create file: "+e.getDetails());throwe;}}}
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrorfromgoogleapiclient.httpimportMediaFileUploaddefupload_appdata():"""Insert a file in the application data folder and prints file Id. Returns : ID's of the inserted files Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """creds,_=google.auth.default()try:# call drive api clientservice=build("drive","v3",credentials=creds)# pylint: disable=maybe-no-memberfile_metadata={"name":"abc.txt","parents":["appDataFolder"]}media=MediaFileUpload("abc.txt",mimetype="text/txt",resumable=True)file=(service.files().create(body=file_metadata,media_body=media,fields="id").execute())print(f'File ID: {file.get("id")}')exceptHttpErroraserror:print(f"An error occurred: {error}")file=Nonereturnfile.get("id")if__name__=="__main__":upload_appdata()
/** * Insert a file in the application data folder and prints file Id * */asyncfunctionuploadAppdata(){// Get credentials and build service// TODO (developer) - Use appropriate auth mechanism for your appconst{GoogleAuth}=require('google-auth-library');const{google}=require('googleapis');constfs=require('fs');constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive.appdata',});constservice=google.drive({version:'v3',auth});constfileMetadata={name:'config.json',parents:['appDataFolder'],};constmedia={mimeType:'application/json',body:fs.createReadStream('files/config.json'),};try{constfile=awaitservice.files.create({requestBody:fileMetadata,media:media,fields:'id',});console.log('File Id:',file.data.id);returnfile.data.id;}catch(err){// TODO(developer) - Handle errorthrowerr;}}
usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Drive.v3;usingGoogle.Apis.Services;namespaceDriveV3Snippets{// Class of demonstrate the use of Drive upload app data. publicclassUploadAppData{/// <summary>/// Insert a file in the application data folder and prints file Id./// </summary>/// <param name="filePath">File path to upload.</param>/// <returns>ID's of the inserted files, null otherwise.</returns>publicstaticstringDriveUploadAppData(stringfilePath){try{/* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */GoogleCredentialcredential=GoogleCredential.GetApplicationDefault().CreateScoped(DriveService.Scope.DriveAppdata);// Create Drive API service.varservice=newDriveService(newBaseClientService.Initializer{HttpClientInitializer=credential,ApplicationName="Drive API Snippets"});varfileMetadata=newGoogle.Apis.Drive.v3.Data.File(){Name="config.json",Parents=newList<string>(){"appDataFolder"}};FilesResource.CreateMediaUploadrequest;using(varstream=newFileStream(filePath,FileMode.Open)){request=service.Files.Create(fileMetadata,stream,"application/json");request.Fields="id";request.Upload();}varfile=request.ResponseBody;// Prints the file id.Console.WriteLine("File ID: "+file.Id);returnfile.Id;}catch(Exceptione){// TODO(developer) - handle error appropriatelyif(eisAggregateException){Console.WriteLine("Credential Not found");}else{throw;}}returnnull;}}}
כדי לחפש קבצים בתיקיית נתוני האפליקציה, מגדירים את השדה spaces לערך appDataFolder ומשתמשים ב-method files.list. בדוגמת הקוד הבאה מוסבר איך לחפש קבצים בתיקיית נתוני האפליקציה באמצעות ספריית לקוח.
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.drive.Drive;importcom.google.api.services.drive.DriveScopes;importcom.google.api.services.drive.model.File;importcom.google.api.services.drive.model.FileList;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.util.Arrays;/** * Class to demonstrate use-case of list 10 files in the application data folder. */publicclassListAppData{/** * list down files in the application data folder. * * @return list of 10 files. */publicstaticFileListlistAppData()throwsIOException{/*Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application.*/GoogleCredentialscredentials=null;try{credentials=GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA));}catch(IOExceptione){e.printStackTrace();}HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Build a new authorized API client service.Driveservice=newDrive.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Drive samples").build();try{FileListfiles=service.files().list().setSpaces("appDataFolder").setFields("nextPageToken, files(id, name)").setPageSize(10).execute();for(Filefile:files.getFiles()){System.out.printf("Found file: %s (%s)\n",file.getName(),file.getId());}returnfiles;}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelySystem.err.println("Unable to list files: "+e.getDetails());throwe;}}}
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordeflist_appdata():"""List all files inserted in the application data folder prints file titles with Ids. Returns : List of items Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """creds,_=google.auth.default()try:# call drive api clientservice=build("drive","v3",credentials=creds)# pylint: disable=maybe-no-memberresponse=(service.files().list(spaces="appDataFolder",fields="nextPageToken, files(id, name)",pageSize=10,).execute())forfileinresponse.get("files",[]):# Process changeprint(f'Found file: {file.get("name")}, {file.get("id")}')exceptHttpErroraserror:print(f"An error occurred: {error}")response=Nonereturnresponse.get("files")if__name__=="__main__":list_appdata()
/** * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *//** * List all files inserted in the application data folder * */asyncfunctionlistAppdata(){// Get credentials and build service// TODO (developer) - Use appropriate auth mechanism for your appconst{GoogleAuth}=require('google-auth-library');const{google}=require('googleapis');constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive.appdata',});constservice=google.drive({version:'v3',auth});try{constres=awaitservice.files.list({spaces:'appDataFolder',fields:'nextPageToken, files(id, name)',pageSize:100,});res.data.files.forEach(function(file){console.log('Found file:',file.name,file.id);});returnres.data.files;}catch(err){// TODO(developer) - Handle errorthrowerr;}}module.exports=listAppdata;
usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Drive.v3;usingGoogle.Apis.Drive.v3.Data;usingGoogle.Apis.Services;namespaceDriveV3Snippets{// Class to demonstrate use-case of Drive's list files in the application data folder.publicclassListAppData{/// <summary>/// List down files in the application data folder./// </summary>/// <returns>list of 10 files, null otherwise.</returns>publicstaticFileListDriveListAppData(){try{/* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */GoogleCredentialcredential=GoogleCredential.GetApplicationDefault().CreateScoped(DriveService.Scope.DriveAppdata);// Create Drive API service.varservice=newDriveService(newBaseClientService.Initializer{HttpClientInitializer=credential,ApplicationName="Drive API Snippets"});varrequest=service.Files.List();request.Spaces="appDataFolder";request.Fields="nextPageToken, files(id, name)";request.PageSize=10;varresult=request.Execute();foreach(varfileinresult.Files){// Prints the list of 10 file names.Console.WriteLine("Found file: {0} ({1})",file.Name,file.Id);}returnresult;}catch(Exceptione){// TODO(developer) - handle error appropriatelyif(eisAggregateException){Console.WriteLine("Credential Not found");}else{throw;}}returnnull;}}}
הורדת קבצים מהתיקייה 'נתוני האפליקציה'
כדי להוריד קובץ מהתיקייה של נתוני האפליקציה, משתמשים ב-method files.get. למידע נוסף ולדוגמאות קוד, אפשר לעיין במאמר הורדת תוכן של קובץ blob.
[[["התוכן קל להבנה","easyToUnderstand","thumb-up"],["התוכן עזר לי לפתור בעיה","solvedMyProblem","thumb-up"],["סיבה אחרת","otherUp","thumb-up"]],[["חסרים לי מידע או פרטים","missingTheInformationINeed","thumb-down"],["התוכן מורכב מדי או עם יותר מדי שלבים","tooComplicatedTooManySteps","thumb-down"],["התוכן לא עדכני","outOfDate","thumb-down"],["בעיה בתרגום","translationIssue","thumb-down"],["בעיה בדוגמאות/בקוד","samplesCodeIssue","thumb-down"],["סיבה אחרת","otherDown","thumb-down"]],["עדכון אחרון: 2025-02-24 (שעון UTC)."],[[["The application data folder is a hidden folder used by your app to store app-specific data, like configuration files, that is only accessible by your application and is automatically deleted when the app is uninstalled."],["Files in this folder do not move between storage locations and to access it, you need to request the `https://www.googleapis.com/auth/drive.appdata` scope."],["To create a file in the application data folder, specify `appDataFolder` in the `parents` property of the file within the `files.create` method."],["To search for files within the application data folder, set the `spaces` field to `appDataFolder` within the `files.list` method."]]],["The *application data folder* stores app-specific data, hidden from users and other apps, automatically created upon file creation attempts. Files within cannot be moved between storage spaces. Access requires the `https://www.googleapis.com/auth/drive.appdata` scope. To create a file, set `appDataFolder` in the file's `parents` property and use the `files.create` method. To search files, set `spaces` to `appDataFolder` and use the `files.list` method. The folder is deleted when the app is uninstalled.\n"]]