javascript - 使用元数据 API 迭代 Google Drive 文件

标签 javascript google-drive-api drive google-drive-realtime-api

我想显示驱动器文件元数据

“图标链接”, “缩略图链接”

驱动器中的每个文件,但仅获取种类、id、名称、mimeType 等字段的输出。而其他字段则不显示。

function loadDriveApi() {
    gapi.client.load('drive', 'v3', listFiles);
}

function listFiles() {
    var request = gapi.client.drive.files.list({});

    request.execute(function(resp) {
        var files = resp.files;
        if (files && files.length > 0) {
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                appendPre(file.iconLink);
            }
        } else {
            appendPre('No files found.');
        }
    });
}

最佳答案

至少你需要范围:https://www.googleapis.com/auth/drive.metadata.readonly + OAuth(API key 和客户端 ID)

您可以在以下位置进行测试:https://developers.google.com/drive/v3/reference/files/list

在“字段”输入中添加:files(iconLink,thumbnailLink)

如果您使用https://apis.google.com/js/api.js ,请务必将您的域名添加到 API-Key -> HTTP-Referrer & Client-ID -> JavaScript-Source & Forwarding-URI (@ https://console.developers.google.com/apis/credentials )

您可以在这里找到基本的gapi使用示例:https://github.com/google/google-api-javascript-client/blob/51aa25bed4f6c36d8e76fd3b9f7e280ded945c98/samples/loadedDiscovery.html

我不久前 promise 了gapi客户端,因为我不喜欢方法中回调和thenables的混合。这对我有用(假设api.js已经加载),但只在其中保存100个文件条目回应。

window.gapiPromisified = {
  apiKey: 'XXXXXXXXXXX',
  clientId: 'XXXXX-XXXXXX.apps.googleusercontent.com'
}

window.gapiPromisified.init = function init () {
  return new Promise(resolve => {
    gapi.load('client:auth2', () => {
      if (!document.getElementById('gapiAuthButton')) {
        let authButton = document.createElement('button')
        authButton.id = 'gapiAuthButton'
        authButton.style.display = 'none'
        authButton.style.marginLeft = 'auto'
        authButton.style.marginRight = 0
        document.body.insertBefore(authButton, document.body.firstChild)
        authButton.addEventListener('click', () => {
          let GoogleAuth = gapi.auth2.getAuthInstance()
          if (GoogleAuth.isSignedIn.get()) {
            GoogleAuth.signOut()
          } else {
            GoogleAuth.signIn()
          }
        })
      }
      gapi.client.setApiKey(this.apiKey)
      gapi.auth2.init({ client_id: this.clientId })
      .then(() => resolve())
    })
  })
}

window.gapiPromisified.signIn = function signIn () {
  return new Promise(resolve => {
    let GoogleAuth = gapi.auth2.getAuthInstance()
    // Listen for sign-in state changes
    GoogleAuth.isSignedIn.listen(isSignedIn => {
      let authButton = document.getElementById('gapiAuthButton')
      if (isSignedIn) {
        authButton.textContent = 'Sign-out'
        resolve()
      } else {
        authButton.textContent = 'Sign-in'
      }
    })
    // Handle the initial sign-in state
    let authButton = document.getElementById('gapiAuthButton')
    let isSignedIn = GoogleAuth.isSignedIn.get()
    authButton.textContent = (isSignedIn) ? 'Sign-out' : 'Sign-in'
    document.getElementById('gapiAuthButton').style.display = 'block'
    if (isSignedIn) {
      resolve()
    } else {
      GoogleAuth.signIn()
    }
  })
}

window.gapiPromisified.getReady = function getReady () {
  if (!gapi.hasOwnProperty('auth2')) {
    return this.init()
    .then(() => this.signIn())
  } else {
    if (gapi.auth2.getAuthInstance().isSignedIn.get()) {
      return Promise.resolve()
    } else {
      return this.signIn()
    }
  }
}

window.gapiPromisified.getScopes = function getScopes (scopes) {
  return new Promise((resolve, reject) => {
    let GoogleUser = gapi.auth2.getAuthInstance().currentUser.get()
    if (GoogleUser.hasGrantedScopes(scopes)) {
      resolve()
    } else {
      // method returns goog.Thenable
      GoogleUser.grant({ 'scope': scopes })
      .then(onFulfilled => {
        resolve(onFulfilled)
      }, onRejected => {
        reject(onRejected)
      })
    }
  })
}

window.gapiPromisified.loadAPI = function loadAPI (urlOrObject) {
  return new Promise((resolve, reject) => {
    // method returns goog.Thenable
    gapi.client.load(urlOrObject)
    .then(onFulfilled => {
      resolve(onFulfilled)
    }, onRejected => {
      reject(onRejected)
    })
  })
}

window.gapiPromisified.metadata = function metadata () {
  return new Promise((resolve, reject) => {
    this.getReady()
    .then(() => this.getScopes('https://www.googleapis.com/auth/drive.metadata.readonly'))
    .then(() => this.loadAPI('https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'))
    .then(() => {
      gapi.client.drive.files.list({
        fields: 'files(iconLink,thumbnailLink)'
      })
      .then(onFulfilled => {
        resolve(onFulfilled)
      }, onRejected => {
        reject(onRejected)
      })
    })
  })
}

window.gapiPromisified.metadata()
.then(res => {
  res.result.files.forEach(file => {
    console.log(file.iconLink)
    console.log(file.thumbnailLink)
  })
})

关于javascript - 使用元数据 API 迭代 Google Drive 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41636049/

相关文章:

javascript - 将 json 扁平化为 csv 格式

javascript - bootstrap popover不显示隐藏的内容包装器

android - 如何下载。使用 Intent 选择器从 Google Drive 中选择的 txt 或 .pdf 文件

google-app-engine - 是否有已发布的 Google API 带宽规范?

android - 获取可与服务器共享的 OAuth2 授权码

c# - 如何通过序列号获取CD/DVD-ROM盘符

java - 如何从 MultipartFile 中提取文件路径

javascript - ng-repeat 中的 Angular 设置 $sce

javascript - ExtJS v3 - 从表单面板内的网格面板访问数据

oauth-2.0 - 使用 "https://www.googleapis.com/auth/drive"范围时出错