出于某种原因,我想从google驱动器中获取文件并在服务器上处理它。从选择器中,我得到了FileID,并将它发送到后端进行下载和处理。因此,在使用googleapis下载文件时,我会得到这个错误。
先决条件
权限我尝试过
我使用的代码来自GitHub
const tmpDir = path.resolve(path.join(os.tmpdir(), "user-sheets"));
const file = path.join(tmpDir, Date.now().toString());
let stream = fs.createWriteStream(file);
let drive = google.drive({
version: "v3",
auth: "MY ACCESS TOKEN",
});
drive.files
.get(
{
fileId: req.body.url,
alt: "media",
oauth_token: "MY ACCESS TOKEN",
},
{
responseType: "stream",
}
)
.then((r) => {
r.data
.on("end", async () => {
console.log("ended");
stream.close();
})
.on("error", function (err) {
console.log("Error during download", err);
res.json({
success: false,
message: "Something went wrong",
error: err,
});
})
.pipe(stream);
})
.catch((e) => {
console.error(e.response);
});
发布于 2020-08-07 15:59:08
在这个答案中,我认为以下几点。
MY ACCESS TOKEN
of auth: "MY ACCESS TOKEN",
是下载文件的有效访问令牌。req.body.url
of fileId: req.body.url,
是文件ID,而不是fileId: req.body.url,
。如果我的猜测不正确,请告诉我。
当我的猜测是正确的,请确认以下修改。
修改点:
MY ACCESS TOKEN
不能直接用于google.drive()
和drive.files.get()
。当这一点反映到您的脚本中时,如下所示。
修改脚本:
发自:
let drive = google.drive({
version: "v3",
auth: "MY ACCESS TOKEN",
});
drive.files
.get(
{
fileId: req.body.url,
alt: "media",
oauth_token: "MY ACCESS TOKEN",
},
{
responseType: "stream",
}
)
至:
var oauth2Client = new google.auth.OAuth2();
oauth2Client.setCredentials({access_token: "MY ACCESS TOKEN"});
const drive = google.drive({
version: "v3",
auth: oauth2Client,
});
drive.files
.get(
{
fileId: req.body.url, // Please use the file ID here.
alt: "media",
},
{ responseType: "stream" }
)
注意:
参考资料:
https://stackoverflow.com/questions/63304429
复制