내가 보려고 만든 블로그

google api사용해서 google drive에 파일 업로드 - 2 본문

c#

google api사용해서 google drive에 파일 업로드 - 2

hjh1023 2022. 10. 18. 18:54
반응형
// service account 계정만들고 다운받은 json파일 경로
private const string PathToServiceAccountKeyFile = @"C:\Users\\Desktop\mygoogleapi.json";
// upload할 파일경로 + 이름
private const string UploadFileName = @"C:\Users\Desktop\aaa.txt";
//구글드라이브의 폴더주소
private const string DirectoryId = "1QM.......";

구글드라이브에 들어가서 폴더 하나 만들고 그 폴더에서 우클릭하고 공유를 누른다.

json파일을 보면 client_email 옆에 텍스트가 있는데 그것을 복사해서 공유에 쓰고 공유 버튼을 누른다.

그리고 test폴더 안에 들어가면 이렇게 나온다. 

구글드라이브 폴더 안에 들어가서 folders/뒤에 있는거 복사해서 DirectoryId에 넣으면 됨

이렇게 업로드 함수를 만들어준다.

public static string DriveUploadBasic(string filePath){
    var credential = GoogleCredential.FromFile(PathToServiceAccountKeyFile)
                    .CreateScoped(DriveService.Scope.Drive);
    // Create Drive API service.
    var service = new DriveService(new BaseClientService.Initializer
    {
        HttpClientInitializer = credential,
        //ApplicationName = "Drive API Snippets"
    });

    // Upload file photo.jpg on drive.
    var fileMetadata = new Google.Apis.Drive.v3.Data.File()
    {
        Name = "upload.txt", //업로드 파일명(드라이브 상에서 보여지는 이름)
        Parents = new List<String>() { DirectoryId }
    };
    FilesResource.CreateMediaUpload request;
    // Create a new file on drive.
    using (var stream = new FileStream(filePath, FileMode.Open))
    {
        // Create a new file, with metadata and stream.
        request = service.Files.Create(
            fileMetadata, stream, "text/plain");
        request.Fields = "id";
        request.Upload();
    }
    var file = request.ResponseBody;
    // Prints the uploaded file id.
    MessageBox.Show("file id" + file.Id);
    return file.Id;
}

사용할때는 이런식으로 버튼이벤트를 만들어주고 위에 UploadFileName변수를 사용해서 업로드 할 파일경로를 지정해준다. 직접 @"C\aaa\Desktop\aaa.txt"이렇게 써줘도 된다.

이건 간단하게 업로드 해봤고 코드정리를 해서 좀 깔끔하게 할수있게 해야겠다.

반응형