【发布时间】:2018-04-10 12:05:17
【问题描述】:
我是 Node JS 的初学者,我想将本地文件上传到谷歌驱动器。我已按照此URL 的说明进行操作。但是当我要运行它时,它会出现“权限不足”之类的错误。请帮助我解决我在其中缺少的内容。
这是我的代码。
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
const OAuth2Client = google.auth.OAuth2;
const SCOPES = ['https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.files.create',
'https://www.googleapis.com/auth/spreadsheets'];
const TOKEN_PATH = 'credentials.json';
// Load client secrets from a local file.
fs.readFile('client_secret.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Sheets API.
authorize(JSON.parse(content), real_upload_files);
});
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new OAuth2Client(client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);});
}
function getNewToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return callback(err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
function real_upload_files(auth) {
var drive = google.drive('v3');
var fileMetadata = {
'name': 'Studentdata.xlsx',
'mimeType': 'application/vnd.google-apps.spreadsheet'
};
var media = {
mimeType: 'text/csv',
body: fs.createReadStream('files/students.xlsx')
};
drive.files.create({
resource: fileMetadata,
media: media,
auth: auth,
fields: 'id',
}, function(err, file) {
if (err) {
console.log(err);
} else {
console.log('File Id: ', file.id);
}
});
}
请帮助我解决我在其中缺少的内容。期待。
【问题讨论】:
-
正如错误所说,您没有足够的权限在驱动器上上传文件。检查您的凭据和权限,看看您是否可以上传文件
-
@Dimitri,是的,我已经检查过了。凭据也是正确的。
-
检查与凭据关联的权限。
-
我们如何检查?
-
您是否尝试查看 google 控制台?