我正在尝试创建一个包含 nextjs (typescript)、nextauth 和 Google Drive API 的项目。它的基本功能是上传、删除和管理文件夹。我已经可以将文件上传到我的 Google 云端硬盘了。
这是API路线-
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){
//console.log("Account Access Token : " , token.accessToken)
if (account) {
token.accessToken = account.access_token;
}
return token
},
async session({ session, token } : any) {
const newSession = {
...session,
accessToken: token.accessToken,
};
//console.log("New Session Object:", newSession);
return newSession;
},
}
})
const handler = NextAuth(authOptions)
export {handler as GET, handler as POST}
and as for the main component or main function that im using for now
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)
console.log("Body Data : ", body)
try {
const response = await fetch(
`https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart` ,
{
method : "POST",
body : body,
headers: {
Authorization: `Bearer ${session.accessToken}`
}
})
console.log("Response : " , response)
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);
}
}
现在我遇到的问题是上传到特定文件夹 即使在验证我的 accessToken 以确保其正常工作并使用 'parents={folderId} 后,它仍然没有遵循上传位置,尽管它仍然上传但仅在默认位置(我的云端硬盘)上,我只是无法正确理解它。如果有人能向我解释并帮助我理解,我将不胜感激。
我相信您的目标如下。
在这种情况下,请按如下方式修改您的脚本。在此修改中,您的请求正文的元数据被修改。
const metadata = {
name:file.name
}
const metadata = {
name: file.name,
parents: ["###"] // Please set the folder ID.
}