애플리케이션 데이터 폴더는 앱에서 구성 파일과 같은 애플리케이션별 데이터를 저장하는 데 사용할 수 있는 특수한 숨겨진 폴더입니다. 애플리케이션 데이터 폴더는 폴더에 파일을 만들려고 할 때 자동으로 생성됩니다.
사용자가 직접 상호작용해서는 안 되는 파일을 저장하는 데 이 폴더를 사용하세요. 이 폴더는 애플리케이션에서만 액세스할 수 있으며 콘텐츠는 사용자와 다른 Drive 앱에 표시되지 않습니다.
appDataFolder의 파일은 저장소 위치 (스페이스) 간에 이동할 수 없습니다. 자세한 내용은 파일 구성을 참고하세요.
애플리케이션 데이터 폴더는 사용자가 MyDrive에서 앱을 제거할 때 삭제됩니다. 사용자는 앱의 데이터 폴더를 수동으로 삭제할 수도 있습니다.
애플리케이션 데이터 폴더 범위
애플리케이션 데이터 폴더에 액세스하려면 먼저 https://www.googleapis.com/auth/drive.appdata 범위에 대한 액세스를 요청해야 합니다. 범위 및 범위에 대한 액세스 권한을 요청하는 방법에 관한 자세한 내용은 API별 승인 및 인증 정보를 참고하세요. 특정 OAuth 2.0 범위에 관한 자세한 내용은 Google API의 OAuth 2.0 범위를 참고하세요.
애플리케이션 데이터 폴더에 파일 만들기
애플리케이션 데이터 폴더에 파일을 만들려면 파일의 parents 속성에 appDataFolder를 지정하고 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;}}}
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;}}}
[[["이해하기 쉬움","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"]]