菜鸟问题,我刚刚开始使用 Google Drive API v3。当我只有 fileId 时,如何从谷歌驱动器下载动态文件。文件可以是图片、pdf 或文档。
我尝试搜索但找不到与此相关的任何引用或示例。
这是我目前所拥有的,但它只下载特定的文件扩展名。
downloadFile(req, res) {
const auth = new google.auth.JWT(
client_email,
null,
private_key,
SCOPES,
);
const { fileId } = req.params;
const drive = google.drive({ version: 'v3', auth});
var dest = fs.createWriteStream('./tmp/downloads/dummy.pdf')
drive.files.get({
fileId,
alt: 'media',
}, {
responseType: 'stream'
}).then((driveResponse) => {
driveResponse.data.on('end', () => {
console.log(`downloading fileID ${fileId}`);
})
.on('error', (err) => {
console.log(err);
})
.on('data', (d) => {
console.log(d);
})
.pipe(dest)
})
.catch((err) => {
console.log(err);
})
}
有没有办法从谷歌驱动器下载动态文件?
最佳答案
我相信你的目标如下。
- 您想使用服务帐户和文件 ID 从 Google 云端硬盘下载文件。
- 文件包括 Google Docs 文件和除 Google Docs 文件之外的文件。
- 您想使用适用于 Node.js 的 googleapis 实现这一目标。
修改点:
- 不幸的是,从
它只下载特定的文件扩展名。
,我无法了解您的详细情况。但我猜你的问题的原因可能是由于同时下载了 Google 文档文件和除 Google 文档文件之外的文件。 - 下载Google Docs文件时,需要使用Drive API中的“Files: export”方法下载文件。
- 下载除Google Docs文件以外的文件时,需要使用Drive API中的“Files: get”方法下载文件。
- 我认为上述情况可能是您遇到问题的原因。
- 为了同时下载 Google Docs 文件和 Google Docs 文件以外的文件,我建议采用以下流程。
- 检查文件 ID 的 mimeType。
- 通过 mimeType 使用每种方法下载文件。
当以上几点反射(reflect)到你的脚本中时,它变成如下。
修改后的脚本:
来自:
var dest = fs.createWriteStream('./tmp/downloads/dummy.pdf')
drive.files.get({
fileId,
alt: 'media',
}, {
responseType: 'stream'
}).then((driveResponse) => {
driveResponse.data.on('end', () => {
console.log(`downloading fileID ${fileId}`);
})
.on('error', (err) => {
console.log(err);
})
.on('data', (d) => {
console.log(d);
})
.pipe(dest)
})
.catch((err) => {
console.log(err);
})
收件人:
drive.files.get({ fileId, fields: "*" }, async (err, { data }) => {
if (err) {
console.log(err);
return;
}
let filename = data.name;
const mimeType = data.mimeType;
let res;
if (mimeType.includes("application/vnd.google-apps")) {
const convertMimeTypes = {
"application/vnd.google-apps.document": {
type:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
ext: ".docx",
},
"application/vnd.google-apps.spreadsheet": {
type:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
ext: ".xlsx",
},
"application/vnd.google-apps.presentation": {
type:
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
ext: ".pptx",
},
};
filename += convertMimeTypes[mimeType].ext;
res = await drive.files.export(
{
fileId,
mimeType: convertMimeTypes[mimeType].type,
},
{ responseType: "stream" }
);
} else {
res = await drive.files.get(
{
fileId,
alt: "media",
},
{ responseType: "stream" }
);
}
const dest = fs.createWriteStream(filename);
res.data
.on("end", () => console.log("Done."))
.on("error", (err) => {
console.log(err);
return process.exit();
})
.pipe(dest);
});
注意事项:
- 在此修改中,我在
convertMimeTypes
准备了 3 种类型的 Google Docs 文件。当您要下载其他mimeTypes时,请修改convertMimeTypes
。例如,在这种情况下,Google Docs 文件将下载为 Microsoft Docs 文件。
引用资料:
关于javascript - 如何从谷歌驱动器下载动态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64337805/