You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js+NextAuth+Google Drive API:指定文件夹上传失败求助

Next.js+NextAuth+Google Drive API 无法上传文件到指定文件夹

我正在开发一个基于Next.js(TypeScript)、NextAuth和Google Drive API的项目,核心功能包含文件上传、删除及文件夹管理。目前已实现基础的文件上传到Google Drive功能,但无法将文件上传到指定文件夹,文件始终默认上传至“我的云端硬盘”。已确认accessToken有效,尝试过添加parents={folderId}参数但无效。

相关代码

API路由代码(app/api/auth/[...nextauth]/route.ts)

import NextAuth from "next-auth/next"
import GoogleProvider from "next-auth/providers/google" 

export const authOptions = ({
    providers: [
        GoogleProvider({
            clientId : process.env.GOOGLE_CLIENT_ID ?? "" ,
            clientSecret : process.env.GOOGLE_CLIENT_SECRET ?? "",
            authorization: { 
              params: { 
                scope: "openid email profile https://www.googleapis.com/auth/drive.file" 
              } 
            },
        })
    ],
    callbacks: {
      async jwt({token, user , account} : any){ 
        if (account) {
          token.accessToken = account.access_token;
        }
        return token
      },
      async session({ session, token } : any) {
        const newSession = {
          ...session,
          accessToken: token.accessToken,
        };
        return newSession;
      },
    }
})
 
const handler = NextAuth(authOptions)
export {handler as GET, handler as POST}

文件上传核心函数

const handleFileUpload = async (e : any) => {
    e.preventDefault()
    const file = e.target.files[0]
    const metadata = {
      name:file.name
    }
    const body = new FormData()
    body.append('metadata', new Blob([JSON.stringify(metadata)],{
      type: "application/json"
    }))
      body.append("file" , file)
 
      try { 
        const response = await fetch(
          `https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart` ,
          { 
            method : "POST",
            body : body,
            headers: {
              Authorization: `Bearer ${session.accessToken}`
            }
        })

        if(response.ok){
          const responseData = await response.json()
          const fileId = responseData.id
          const fileUrl = `http://drive.google.com/file/d/${fileId}/view`  
        } 
      } catch (error){
        console.error('Error uploading file:', error);  
      }
  } 

问题分析与解决思路

1. 修正Metadata中的parents字段

Google Drive API要求指定文件夹时,需在metadata对象中添加parents数组字段(而非URL参数),数组中传入目标文件夹的ID。你之前的尝试可能是把parents放在了错误的位置。

修改后的metadata代码:

const metadata = {
  name: file.name,
  parents: ["TARGET_FOLDER_ID"] // 替换为你的目标文件夹ID,注意是数组格式
}

2. 确认权限范围与文件夹授权

你当前使用的drive.file权限范围是有限权限:仅能访问通过你的应用创建的文件,或用户明确授权给应用的特定文件/文件夹。如果目标文件夹不是通过该应用创建,且用户未授权应用访问它,上传就会失败并默认放到“我的云端硬盘”。

解决方式:

  • 若要保持drive.file的最小权限,需先让用户授权访问目标文件夹(可通过Google Picker组件让用户选择文件夹,或调用Drive API的权限接口申请访问);
  • 若不需要严格限制权限,可将scope改为https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive(但此权限范围更大,需谨慎使用)。

3. 验证请求数据正确性

可在上传前打印metadata的JSON字符串,确认parents字段已正确包含;也可通过Chrome开发者工具查看请求的FormData内容,确保metadata部分已正确序列化。

4. 确认文件夹ID有效性

确保你使用的文件夹ID正确无误:可通过Google Drive网页版打开目标文件夹,从URL中提取ID(URL格式为https://drive.google.com/drive/folders/[FOLDER_ID])。

内容的提问来源于stack exchange,提问作者user14670265

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 19:10:11