嘿,我已经按照云端硬盘快速入门指南中的步骤进行操作,并使用以下范围生成了token.json:
const SCOPES = [
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.file'
];
然后我正在运行以下代码,尝试将文件创建/上传到Google驱动器。
async function testing() {
let driveFolder = 'FOLDERID';
let res;
try {
const oauth2Client = new google.auth.OAuth2(
credentials.client_id,
credentials.client_secret,
credentials.redirect_uris
);
await oauth2Client.setCredentials({
...tokenInfo
});
console.log('=== completed drive authentication', oauth2Client);
const drive = await google.drive({
version: 'v3',
auth: await oauth2Client
});
console.log('=== Initialised Drive API');
res = await drive.files.create({
parameters :{
uploadType: 'resumable'
},
requestBody: {
name: 'Testing.txt',
mimeType: 'text/plain',
parents: [driveFolder]
},
media: {
mimeType: 'text/plain',
body: 'Hello world!!!'
}
});
console.log('=== Completed Report UPLOAD:', res);
return;
} catch (err) {
console.error('ERROR: \n', err);
}
}
请求完成但未捕获到错误,但返回的响应未定义。 最后两个日志显示以下内容
=== completed drive authentication OAuth2Client {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
transporter: DefaultTransporter {},
credentials:
{ access_token:
'ACCESS TOKEN STRING',
refresh_token:
'REFRESH TOKEN STRING',
scope:
'https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.appdata',
token_type: 'Bearer',
expiry_date: 1551070810157 },
certificateCache: null,
certificateExpiry: null,
refreshTokenPromises: Map {},
_clientId:'CLIENT ID STRING VALUE',
_clientSecret: 'CLIENT SECRET VALUE',
redirectUri: [ 'REDIRECT URL', 'http://localhost' ],
authBaseUrl: undefined,
tokenUrl: undefined,
eagerRefreshThresholdMillis: 300000 }
=== Initialised Drive API
=== Completed Report UPLOAD: undefined
答案 0 :(得分:0)
您可以从文档中尝试quickstart using NodeJS:
// change the scopes
const SCOPES = [ 'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.file'];
function uploadFile(auth){
var drive = google.drive('v3');
var fileMetadata = {
'name': 'Some.jpg' // name of the file
};
var media = {
mimeType: 'image/jpeg',
resumable: true,
//PATH OF THE FILE FROM YOUR COMPUTER
body: fs.createReadStream('/usr/local/google/home/malicdemj/Desktop/blue-cyber-future-technology-concept-background_42077-488.jpg')
};
drive.files.create({
auth: auth,
resource: fileMetadata,
media: media,
fields: 'id'
}, function (err, file) {
if (err) {
// Handle error
console.error(err);
} else {
console.log('File Id: ', file.data.id);
}
});
}
驱动器中的上传文件:
另外,请检查此SO post以获得更多详细信息。