如何将裁剪后的Base64图片上传至Google Drive?(Node.js/前端)
解决方案:Base64裁剪图上传Google Drive(后端中转/前端直传)
方案一:前端传Base64到Node.js后端转Buffer上传
前端代码(修正FormData传参方式)
你之前用FormData拿到字符串是因为直接把完整Base64串塞进去了,正确做法是先剥离data:image/jpeg;base64,前缀,转成Blob再传入FormData:
// 假设裁剪后得到的Base64字符串为cropImageBase64 const base64Raw = cropImageBase64.replace(/^data:image\/jpeg;base64,/, ''); const uint8Array = Uint8Array.from(atob(base64Raw), c => c.charCodeAt(0)); const blob = new Blob([uint8Array], { type: 'image/jpeg' }); const formData = new FormData(); formData.append('croppedImage', blob, 'cropped.jpg'); // 第三个参数指定文件名 // 发送请求到后端 fetch('/upload-to-drive', { method: 'POST', body: formData });
Node.js后端代码(接收并获取Buffer)
用express-fileupload接收时,文件对象的data属性就是直接可用的Buffer:
const express = require('express'); const fileUpload = require('express-fileupload'); const { google } = require('googleapis'); const app = express(); app.use(fileUpload()); app.post('/upload-to-drive', async (req, res) => { if (!req.files?.croppedImage) { return res.status(400).send('未上传文件'); } // 直接获取文件Buffer const fileBuffer = req.files.croppedImage.data; // 调用Google Drive API上传(需提前配置服务账号密钥) const auth = new google.auth.GoogleAuth({ keyFile: 'service-account-key.json', scopes: ['https://www.googleapis.com/auth/drive'] }); const drive = google.drive({ version: 'v3', auth }); try { const uploadRes = await drive.files.create({ requestBody: { name: '裁剪后的图片.jpg', parents: ['目标文件夹ID'] // 可选,指定上传目录 }, media: { mimeType: 'image/jpeg', body: fileBuffer } }); res.send(`上传成功,文件ID:${uploadRes.data.id}`); } catch (err) { console.error(err); res.status(500).send('上传失败'); } }); app.listen(3000, () => console.log('服务运行在3000端口'));
如果不想用express-fileupload,也可以直接传Base64字符串(剥离前缀),后端手动转Buffer:
// 前端 fetch('/upload-base64', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ base64: base64Raw }) }); // 后端 app.post('/upload-base64', async (req, res) => { const fileBuffer = Buffer.from(req.body.base64, 'base64'); // 后续上传Google Drive逻辑同上 });
方案二:前端直接上传到Google Drive
无需后端中转,直接在前端调用Google Drive API,步骤如下:
- 先在Google Cloud Console创建项目,启用Drive API,配置OAuth 2.0客户端ID(允许你的前端域名)。
- 前端实现代码:
// 加载Google API客户端 async function initDriveApi() { await gapi.load('client:auth2', async () => { await gapi.client.init({ clientId: '你的OAuth客户端ID', scope: 'https://www.googleapis.com/auth/drive.file' }); }); } // 上传裁剪后的图片 async function uploadToDrive(cropImageBase64) { // 转成Blob const base64Raw = cropImageBase64.replace(/^data:image\/jpeg;base64,/, ''); const uint8Array = Uint8Array.from(atob(base64Raw), c => c.charCodeAt(0)); const blob = new Blob([uint8Array], { type: 'image/jpeg' }); // 授权登录(未登录则触发Google账号登录) const authInstance = gapi.auth2.getAuthInstance(); if (!authInstance.isSignedIn.get()) { await authInstance.signIn(); } // 构造上传请求 const metadata = { name: '裁剪后的图片.jpg', parents: ['目标文件夹ID'] // 可选 }; const formData = new FormData(); formData.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' })); formData.append('file', blob); try { const token = authInstance.currentUser.get().getAuthResponse().access_token; const response = await fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', { method: 'POST', headers: { 'Authorization': `Bearer ${token}` }, body: formData }); const data = await response.json(); console.log('上传成功,文件ID:', data.id); } catch (err) { console.error('上传失败:', err); } }
注意:前端直传需要用户登录Google账号,且需在Google Cloud Console正确配置授权域名和API权限范围。
内容的提问来源于stack exchange,提问作者karthi keyan
相关产品推荐
相关产品推荐

