上传文件至Google Drive时遭遇权限不足问题求助
Let’s tackle that frustrating "INSUFFICIENT PERMISSION" error you’re hitting. I’ve spotted a couple of key issues in your code and setup that are likely causing this, along with straightforward fixes:
1. Fix the Syntax Error in File Metadata
First, there’s a tiny but critical syntax mistake in your fileMetadata object—you’re missing a comma after the 'name' property. This breaks the object structure, which can lead to unexpected API behavior, including permission-related errors if the parent folder isn’t parsed correctly.
Corrected fileMetadata:
var fileMetadata = { 'name': 'green.png', parents: [folderId] };
2. Clean Up Scopes & Refresh Your Access Token
While your current scopes include write permissions, having redundant scopes can cause confusion, and old access tokens won’t automatically pick up new scope changes. Here’s how to fix this:
- Simplify your scopes to only what’s necessary: For uploading files to a specific folder,
https://www.googleapis.com/auth/drive.fileis perfect—it grants access only to files created by your app, keeping permissions tight and avoiding conflicts. - Delete your existing
credentials.json(the token file) so your app will prompt you to re-authenticate with the updated scopes. This ensures the new token has the correct permissions attached.
Updated SCOPES line:
const SCOPES = ['https://www.googleapis.com/auth/drive.file'];
3. Verify Folder Permissions
Double-check that the Google account you’re using to authenticate has edit access to the target folder (1AM07eNAJz5D4oFa5ZB-0ygOa_tVjoAgR). If the account only has read access, even the right scopes won’t let you upload files there.
Full Corrected Code
Here’s your code with all fixes applied, plus a small addition to send a success response to the client:
var path = require("path"); const fs = require('fs'); const readline = require('readline'); const {google} = require('googleapis'); const OAuth2Client = google.auth.OAuth2; const TOKEN_PATH = 'credentials.json'; var multipart = require('connect-multiparty'); var multipartMiddleware = multipart(); var multer = require("multer"); var upload = multer({dest: "./uploads"}); // Simplified, necessary scope for file uploads const SCOPES = ['https://www.googleapis.com/auth/drive.file']; module.exports=function(app){ app.post("/upload2", upload.array('file', 4) , function(req, res, next){ fs.readFile('client_secret.json', (err, content) => { if (err) return console.log('Error loading client secret file:', err); authorize(JSON.parse(content), UploadFiles); }); function authorize(credentials, callback) { const {client_secret, client_id, redirect_uris} = credentials.installed; const oAuth2Client = new OAuth2Client(client_id, client_secret, redirect_uris[0]); fs.readFile(TOKEN_PATH, (err, token) => { if (err) return getAccessToken(oAuth2Client, callback); oAuth2Client.setCredentials(JSON.parse(token)); callback(oAuth2Client); }); } function UploadFiles(auth) { console.log(auth) const drive = google.drive({version: 'v3', auth}); var folderId = '1AM07eNAJz5D4oFa5ZB-0ygOa_tVjoAgR'; // Fixed comma in fileMetadata var fileMetadata = { 'name': 'green.png', parents: [folderId] }; var media = { mimeType: 'image/png', body: fs.createReadStream('./img/green.png') }; drive.files.create({ resource: fileMetadata, media: media, fields: 'id' }, function (err, file) { if (err) { console.log(err); res.status(500).send(`Upload error: ${err.message}`); } else { console.log('File Id: ', file.id); res.status(200).send(`File uploaded successfully! File ID: ${file.id}`); } }); } }) }
Final Steps to Test
- Delete the existing
credentials.jsontoken file from your project. - Run your app and trigger the
/upload2endpoint. You’ll be prompted to re-authenticate with your Google account. - Grant the requested permissions (your app will only ask for access to files it creates).
- Try uploading
green.pngagain—this should resolve the permission error.
内容的提问来源于stack exchange,提问作者Tom Frazzitta

