2016-12-19 1 views
2

Google 드라이브에서 C#을 사용하여 브라우저에서 파일을 볼 수 있습니까? Google api에서 일부 시도했습니다. 항상 로그인 세부 정보를 요구합니다. 어떻게 C#을 사용하여 브라우저에서 파일을 볼 수 있습니까?C 드라이브를 사용하여 브라우저에서 Google 드라이브의 파일을 볼 수 있습니까?

여기

나는 시도했다

public ActionResult GetDriveFile() 
    { 
     string filePath = System.Web.HttpContext.Current.Server.MapPath("~/client_secret.json"); 
     //string filePath = System.Web.HttpContext.Current.Server.MapPath("~/MyProject-e09c7c94100a.json"); 
     string userName = "[email protected]"; 

     //GoogleCredential credential; 
     //string[] Scopes = { Google.Apis.Drive.v2.DriveService.Scope.Drive }; 

     //using (var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) 
     //{ 
     // credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes); 
     //} 

     //var driveService = new Google.Apis.Drive.v2.DriveService(new BaseClientService.Initializer() 
     //{ 
     // HttpClientInitializer = credential, 
     // ApplicationName = "Test", 
     //}); 


     var driveService = AuthenticateOauth(filePath, userName); 

     List<Google.Apis.Drive.v3.Data.File> allFiles = retrieveAllFiles(driveService); 

     string fileID = allFiles.Where(x => x.Name.Contains("sample.jpg")).Select(y => y.Id).FirstOrDefault(); 

     //DownloadFile(driveService); 

     string fileLink = GetFileLink(fileID); 

     return Redirect(fileLink); 
    } 



public static Google.Apis.Drive.v3.DriveService AuthenticateOauth(string clientSecretPath, string userName) 
    { 
     try 
     { 
      if (string.IsNullOrEmpty(userName)) 
       throw new Exception("userName is required."); 
      if (!System.IO.File.Exists(clientSecretPath)) 
       throw new Exception("clientSecretJson file does not exist."); 

      // These are the scopes of permissions you need. It is best to request only what you need and not all of them 
      string[] scopes = new string[] { Google.Apis.Drive.v3.DriveService.Scope.Drive };     // View and manage the files in your Google Drive   
      UserCredential credential; 
      using (var stream = new System.IO.FileStream(clientSecretPath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) 
      { 
       string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); 
       credPath = System.IO.Path.Combine(credPath, ".credentials/apiName"); 

       // Requesting Authentication or loading previously stored authentication for userName 
       credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, 
                     scopes, 
                     userName, 
                     CancellationToken.None, 
                     new Google.Apis.Util.Store.FileDataStore(credPath, true)).Result; 
      } 

      // Create Drive API service. 
      return new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer() 
      { 
       HttpClientInitializer = credential, 
       ApplicationName = "Drive Authentication Sample", 
      }); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Create Oauth2 DriveService failed" + ex.Message); 
      throw new Exception("CreateOauth2DriveFailed", ex); 
     } 
    } 

는, 사람이 이에 대해 어떤 생각을하세요?

+0

* 사용자는 파일에 액세스 할 수 있지만 나머지 국가는 액세스 할 수 없습니다. Google 드라이브의 파일로 사용자를 리디렉션하면 액세스 할 수있는 명시 적 권한이 필요합니다. 즉, 공개로 설정하거나 개별적으로 액세스해야하는 각 사용자에게 액세스 권한을 부여해야합니다. 유일한 다른 옵션은 다운로드하여 서버에서 직접 응답으로 반환하는 것입니다. 이렇게하면 응용 프로그램에 대해서만 권한을 부여 할 수 있지만 추가 및 위 아래 대역폭을 사용하게됩니다. –

답변

0

Permissions: create을 사용하는 사용자와 파일을 공유 할 때 알림을 보낼 수있는 옵션이 있습니다. 그러면 파일이 공유됩니다.

File.get은 파일 resource을 반환합니다. fields = *를 추가하거나 file.get에서 메타 데이터를 많이 얻지는 않습니다.

webViewLink
브라우저에서 관련 Google 편집기 또는 뷰어로 파일을 여는 링크.

기본적으로 문제가되는 사용자가 액세스 권한을 가진 경우이 링크가 다시 파일로 전송됩니다. 내가 알아낼 수 없었다 이것이

https://docs.google.com/document/d/xWau_bNrntLBDDFjwUPBDkL3_oBW3hthavaVF8Ed1mbA

같은 뭔가 그래서 나는 비록 그 일을하는 방법이 있다고 가정 웹 사이트에 당신이 할 수있는 공유 가능한 링크를 만드는 방법입니다 API도 있습니다. 현재 나는 파일이 공개되어 있어야하거나 사용자가 webview 링크를 다시 받기 전에 액세스 권한이 있어야한다고 생각합니다.

+0

안녕하십니까. –

+0

위의 링크와 관련하여 브라우저에 특정 파일을 보려면 google 계정에 로그인해야합니다 (액세스 권한이있는 경우). * WebViewLink * 및 * WebContentLink *에 대해 항상 * null * 값을 얻고있는 한 가지, * WebViewLink *를 제대로 얻으려면 내 계정이나 코드에서 수행해야하는 다른 구성이 있습니까? –

+0

만약 그렇다면 당신은 yes 파일에 접근해야합니다. 당신이 필드를 얻고 있다고 가정하면 왜 그것이 null이 될지 말하지 않습니다. 않는 한 그것은 아마 Google 드라이브 유형 파일이 아닙니다. 액세스하려는 파일의 유형은 무엇입니까? – DaImTo

관련 문제