Last active
May 14, 2024 11:47
-
-
Save MWaris97/2601a01f9cf7b871a1b3ea2d5e152e1f to your computer and use it in GitHub Desktop.
Code for uploading files to google drive with service account using Nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const createReadStream = require('fs').createReadStream; | |
| const path = require('path'); | |
| const process = require('process'); | |
| const { google } = require('googleapis'); | |
| // Downloaded from while creating credentials of service account | |
| const pkey = require('./pk.json'); | |
| const SCOPES = ['https://www.googleapis.com/auth/drive.file']; | |
| /** | |
| * Authorize with service account and get jwt client | |
| * | |
| */ | |
| async function authorize() { | |
| const jwtClient = new google.auth.JWT( | |
| pkey.client_email, | |
| null, | |
| pkey.private_key, | |
| SCOPES | |
| ) | |
| await jwtClient.authorize(); | |
| return jwtClient; | |
| } | |
| /** | |
| * Create a new file on google drive. | |
| * @param {OAuth2Client} authClient An authorized OAuth2 client. | |
| */ | |
| async function uploadFile(authClient) { | |
| const drive = google.drive({ version: 'v3', auth: authClient }); | |
| const file = await drive.files.create({ | |
| media: { | |
| body: createReadStream('filename') | |
| }, | |
| fields: 'id', | |
| requestBody: { | |
| name: path.basename('filename'), | |
| }, | |
| }); | |
| console.log(file.data.id) | |
| } | |
| //authorize().then(uploadFile).catch(console.error); |
Author
The file should be there on the google drive. Can you try listing it with this utility that I built
The listing worked and returned all the files I've uploaded with the IDs. But I can't still see the files in my Drive. The storage info on my Drive shows that there are some files. Although I can't see them. It's not much of a problem because I can still get the files using the file ID. Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After uploading the files, I could not find the files on my Google Drive. The file ID was printed as stated in the article that led me here.