[英]Google Drive API download NODE.JS sample doesn't work
這是我基於Google的代碼:“以下是使用我們的Drive API客戶端庫執行文件下載的示例。” NODE.JS
const fs = require('fs')
const google = require('googleapis')
const googleAuth = require('google-auth-library')
const SCOPES = ['https://www.googleapis.com/auth/drive'] // Full, permissive scope to access all of a user's files, excluding the Application Data folder. Request this scope only when it is strictly necessary.
const TOKEN_DIR = './credentials/'
const TOKEN_PATH = TOKEN_DIR + 'token4joeDlEs6.json'
const CLIENT_SECRET_FILEPATH = 'client_secret.json'
var clientSecretStr = fs.readFileSync(CLIENT_SECRET_FILEPATH).toString('utf-8')
var tokenStr = fs.readFileSync(TOKEN_PATH).toString('utf-8')
var credentials = JSON.parse(clientSecretStr)
var clientSecret = credentials.installed.client_secret
var clientId = credentials.installed.client_id
var redirectUrl = credentials.installed.redirect_uris[0]
var auth = new googleAuth()
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl)
oauth2Client.credentials = JSON.parse(tokenStr)
var drive = google.drive('v3');
// ["Examples"-NODE.JS tab](https://developers.google.com/drive/v3/web/manage-downloads)
var fileId = 'OBFUSCATED' // Safeway (OBFUSCATED)
var dest = fs.createWriteStream('out/safeway.txt')
drive.files.get({
auth: oauth2Client,
fileId: fileId,
//alt: 'media'
})
.on('end', function () {
console.log('Done');
})
.on('error', function (err) {
console.log('Error during download', err);
})
.pipe(dest);
$ node joeDlSample.js
Done
$
out / safeway.txt包含我的購物清單。 :)
out / safeway.txt包含
{
"access_token" : "OBFUSCATED.OBFUSCATED",
"expires_in" : 3600,
"token_type" : "Bearer"
}
我還上傳了.jpg圖片,但未注釋alt: media
代碼中的alt: media
行
out / elb.jpg包含elb圖片
out / elb.jpg包含
{
"access_token" : "OBFUSCATED.OBFUSCATED",
"expires_in" : 3600,
"token_type" : "Bearer"
}
通過結合使用Drive NodeJS快速入門和NodeJS的下載文件示例,我設法使Drive API的下載文件正常工作。
在NodeJS快速入門中,有以下代碼行:
authorize(JSON.parse(content), listFiles);
我創建了自己的downloadFile
函數來下載文件而不是列出文件,並將上述行修改為
authorize(JSON.parse(content), downloadFile);
這是NodeJS示例的downloadFile
函數部分:
function downloadFile(auth){
var service = google.drive('v3');
var fileId = 'FILE_ID_OF_SHOPPINGLIST_TEXT_FILE';
var dest = fs.createWriteStream('/usr/local/google/home/username/Downloads/shoppinglist.txt');
service.files.get({
auth: auth,
fileId: fileId,
alt: 'media'
})
.on('end', function () {
console.log('Done');
})
.on('error', function (err) {
console.log('Error during download', err);
})
.pipe(dest);
}
我的下載文件夾中的下載文件:
為我工作:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.