我陷入了这段代码,我有一个将文件上传到Google云端硬盘的功能。效果很好!但是我想在文件上传完成后执行附加功能。 我尝试使用.then和新的Promise,但不起作用
有我的代码(功能):
var { google } = require("googleapis");
var drive = google.drive("v3");
var key = require("./private_key.json");
var path = require("path");
var fs = require("fs");
controller.uploadImage = (req, res) => {
var file_uploaded_to_drive = false;
var jwToken = new google.auth.JWT(
key.client_email,
null,
key.private_key, ["https://www.googleapis.com/auth/drive"],
null
);
jwToken.authorize((authErr) => {
if (authErr) {
console.log("error : " + authErr);
return;
} else {
console.log("Authorization accorded");
}
});
var file_name = 'Imagen No Subida....';
if (req.files) {
var filePath = req.files.file.path;
var fileSplit = filePath.split('\\');
var fileName = fileSplit[2];
var extSplit = fileName.split('\.');
var fileExt = extSplit[1];
if (fileExt == 'png' || fileExt == 'jpg' || fileExt == 'rar' || fileExt == 'mp3' || fileExt == 'mp4' || fileExt == 'wmv') {
var folderId = "1HMTg8nv-FMf0N4BqNChF3LEW6EibK4FG";
var fileMetadata = {
'name': req.files.file.name,
parents: [folderId]
};
var media = {
mimeType: 'application/octet-stream',
body: fs.createReadStream('../uploads/' + fileName)
};
drive.files.create({
auth: jwToken,
resource: fileMetadata,
media: media,
fields: 'id'
}, function(err, file) {
if (err) {
console.error(err);
} else {
console.log('File Id: ', file.data.id);
// ---- HERE THE FILE IS UPLOADED I THINK----
return res.status(200).send({
files: req.files,
"codigo": file.data.id,
});
//AFTER THE UPLOAD I WANT TO EXECUTE SOMETHING LIKE THIS
// .then({
// console.log( 'Upload Complete')
// });
}
});
} else {
fs.unlink(filePath, (err) => {
return res.status(200).send({ message: 'La extensión no es valida' });
});
}
} else {
return res.status(200).send({
message: 'File doesn't uploaded'
});
}
}
如果我将控制台放在代码的底部,则首先执行此操作,然后执行上载。 有什么建议吗?