NEW ANSWER (Old answer issue fixed here)
The problem might be caused by not handling the read stream correctly with Axios. Instead of passing the read stream directly to axios.put(), you should pipe the read stream to the PassThrough stream and provide it to axios.put().
import axios from 'axios';
import { google } from 'googleapis';
import fs from 'fs';
import path from 'path';
import { PassThrough } from 'stream';
export async function uploadFile(auth) {
const fileMetadata = {
name: FILENAME,
};
const filePath = path.join(homedir(), 'Pictures', FILENAME);
const fileSize = fs.statSync(filePath).size;
const media = {
mimeType: FILETYPE,
};
const drive = google.drive({ version: 'v3', auth });
try {
const uploadUrlRes = await drive.files.create({
requestBody: fileMetadata,
media: media,
fields: 'id',
uploadType: 'resumable',
});
const uploadUrl = uploadUrlRes.data;
const fileWrite = fs.createReadStream(filePath);
const passThrough = new PassThrough();
fileWrite.pipe(passThrough);
const axiosConfig = {
headers: {
'Content-Type': media.mimeType,
'Content-Length': fileSize,
},
onUploadProgress: (evt) => {
const progress = Math.round((evt.loaded / fileSize) * 100);
console.log(progress);
},
};
const res = await axios.put(uploadUrl, passThrough, axiosConfig);
console.log(res.data);
} catch (error) {
console.error('Error uploading file:', error);
}
}
OLD ANSWER.
Using Axios to handle the upload and its progress. First create a resumable upload session with Google Drive API by calling drive.files.create() with the uploadType parameter set to 'resumable'. This will return a resumable session URI, which can use with Axios to upload the file.
Now, configure Axios with the appropriate headers and onUploadProgress event handler. We then use the axios.put() method to upload the file to the resumable session URI.
import axios from 'axios';
import { google } from 'googleapis';
import fs from 'fs';
import path from 'path';
export async function uploadFile(auth) {
const fileMetadata = {
name: FILENAME,
};
const fileWrite = fs.createReadStream(path.join(homedir(), 'Pictures', FILENAME));
const fileSize = fs.statSync(path.join(homedir(), 'Pictures', FILENAME)).size;
const media = {
mimeType: FILETYPE,
body: fileWrite,
};
const drive = google.drive({ version: 'v3', auth });
try {
const uploadUrlRes = await drive.files.create({
requestBody: fileMetadata,
media: media,
fields: 'id',
uploadType: 'resumable'
});
const uploadUrl = uploadUrlRes.data;
const axiosConfig = {
headers: {
'Content-Type': media.mimeType,
'Content-Length': fileSize,
},
onUploadProgress: (evt) => {
const progress = Math.round((evt.loaded / fileSize) * 100);
console.log(progress);
},
};
const res = await axios.put(uploadUrl, fileWrite, axiosConfig);
console.log(res.data);
} catch (error) {
console.error('Error uploading file:', error);
}
}