[英]How to Download files using Google Drive API REST?
I am having difficulties in downloading files from Google Drive using the v3 REST API.我在使用 v3 REST API 从 Google Drive 下载文件时遇到困难。 I am making the request via axios and getting the array buffer as a response, however, the buffer when saved to a file is corrupted.
我通过 axios 发出请求并获取数组缓冲区作为响应,但是,保存到文件时的缓冲区已损坏。
These are the response headers that i am getting on making the request:这些是我在发出请求时收到的响应标头:
HTTP/1.1 200 date: Mon, 07 Oct 2019 21:36:21 GMT
content-encoding: gzip
expires: Mon, 07 Oct 2019 21:36:21 GMT
server: GSE
content-type: text/plain; charset=UTF-8
vary: Origin, X-Origin
cache-control: private, max-age=0, must-revalidate, no-transform
Content-Type: application/pdf
{file content}
i am guessing the gzip compression and utf-8 encoding is what is messing up with the file.我猜是 gzip 压缩和 utf-8 编码是什么弄乱了文件。 I also downloaded the same file via the browser and compared their raw contents and surely the content differs in both the files.
我还通过浏览器下载了相同的文件并比较了它们的原始内容,当然这两个文件的内容都不同。 Any help will be appreciated.
任何帮助将不胜感激。
EDIT:编辑:
This is how I am making the request currently for which I am getting the above headers and file contents as a response.这就是我当前发出请求的方式,我正在为此获取上述标头和文件内容作为响应。
const {data} = await axios.get(`${exportLink}&${qs.stringify({access_token: access_token})}`, {responseType: 'arraybuffer',
timeout: 30000,})
As @Suhakar RS said, you can look at this example to learn how to do it.正如@Suhakar RS所说,您可以查看此示例以了解如何操作。
This is the relevant part:这是相关部分:
drive.files
.get({fileId, alt: 'media'}, {responseType: 'stream'})
.then(res => {
return new Promise((resolve, reject) => {
const filePath = path.join(os.tmpdir(), uuid.v4());
console.log(`writing to ${filePath}`);
const dest = fs.createWriteStream(filePath);
let progress = 0;
res.data
.on('end', () => {
console.log('Done downloading file.');
resolve(filePath);
})
.on('error', err => {
console.error('Error downloading file.');
reject(err);
})
.on('data', d => {
progress += d.length;
if (process.stdout.isTTY) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(`Downloaded ${progress} bytes`);
}
})
.pipe(dest);
});
});
Notice how the file is requested as a stream and is written in the same format.请注意文件是如何被请求为 stream 的,并以相同的格式写入。
Hope this helps!希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.