本分步指南介绍了如何使用 Node.js、Express 和 Multer 构建用于将文件上传到 Google Drive 的 Web 表单。
Web 表单将文件编码为 multipart/form-data 并在POST
请求中将数据发送到 Node.js 应用程序。 Multer 是一个用于处理多部分表单数据的 Express 中间件。
1. 创建 HTML 表单
HTML 表单包含允许上传多个文件的文件上传字段。它还包括受访者姓名、电子邮件和国家/地区的文本字段。
提交表单时,它使用浏览器的内置文件 API 将文件发送到 Node.js 应用程序。
<! DOCTYPE html > < html > < head > < meta charset = " utf-8 " /> < meta name = " viewport " content = " width=device-width, initial-scale=1 " /> </ head > < body > < form > < input type = " file " name = " Files " required multiple /> < input type = " text " name = " Name " placeholder = " Name " /> < input type = " email " name = " Email Address " placeholder = " Email " required /> < input type = " text " name = " Country " placeholder = " Country " /> < button type = " submit " > Submit </ button > </ form > </ body > < script > const formElem = document . querySelector ( 'form' ) ; formElem . addEventListener ( 'submit' , async ( e ) => { e . preventDefault ( ) ; await fetch ( '/upload' , { method : 'POST' , body : new FormData ( formElem ) , } ) ; } ) ; </ script > </ html >
2. 创建 Node.js 应用程序
Node.js 应用程序将从表单接收文件并将它们上传到 Google Drive。主路由将呈现包含表单的 HTML 页面。
// index.js const express = require ( 'express' ) ; const uploadRouter = require ( './router' ) ; const app = express ( ) ; app . get ( '/' , ( _ , res ) => { res . sendFile ( ` ${ __dirname } /index.html ` ) ; } ) ; app . use ( express . json ( ) ) ; app . use ( express . urlencoded ( { extended : true } ) ) ; app . use ( uploadRouter ) ; app . listen ( 8080 , ( ) => { console . log ( 'Form running on port 8080' ) ; } ) ;
3.谷歌驱动上传路由器
Multer 将 body 对象和 files 对象添加到请求对象。 body 对象包含表单的文本字段,而 files 对象将包含通过表单上传的文件。
您可以使用服务帐户对 Google Drive 服务进行身份验证。在 Google 云端硬盘中创建一个新文件夹,将该文件夹与服务帐户的电子邮件地址共享,并将 DRIVE_FOLDER_ID 替换为该文件夹的 ID。
// router.js const stream = require ( 'stream' ) ; const express = require ( 'express' ) ; const multer = require ( 'multer' ) ; const { google } = require ( 'googleapis' ) ; const uploadRouter = express . Router ( ) ; const upload = multer ( ) ; const uploadFile = async ( fileObject ) => { const bufferStream = new stream . PassThrough ( ) ; bufferStream . end ( fileObject . buffer ) ; const { data } = await google . drive ( { version : 'v3' } ) . files . create ( { media : { mimeType : fileObject . mimeType , body : bufferStream , } , requestBody : { name : fileObject . originalname , parents : [ 'DRIVE_FOLDER_ID' ] , } , fields : 'id,name' , } ) ; console . log ( ` Uploaded file ${ data . name } ${ data . id } ` ) ; } ; uploadRouter . post ( '/upload' , upload . any ( ) , async ( req , res ) => { try { const { body , files } = req ; for ( let f = 0 ; f < files . length ; f += 1 ) { await uploadFile ( files [ f ] ) ; } console . log ( body ) ; res . status ( 200 ) . send ( 'Form Submitted' ) ; } catch ( f ) { res . send ( f . message ) ; } } ) ; module . exports = uploadRouter ;