OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Google Drive API upload to specific folder

  • Thread starter Thread starter user14670265
  • Start date Start date
U

user14670265

Guest
I'm trying to create a project that contains nextjs (typescript), nextauth and Google Drive API. Its basic features would be upload, delete and manage folders. I got to the point that I am able to upload files to me Google Drive.

This is the API routes-

Code:
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;
      },
    }
})

Code:
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);  
      }
  }

Now what I'm having a issue with is the uploading to a specific folder even after verifying my accessToken to make sure its working properly and using 'parents={folderId} its still not following the upload location, though it still upload but only on the default location (My Drive), I just can't understand it properly. I would appreciate if anyone can explain to me and help me understand here.

The code is from

<p>I'm trying to create a project that contains nextjs (typescript), nextauth and Google Drive API. Its basic features would be upload, delete and manage folders. I got to the point that I am able to upload files to me Google Drive.</p>
<p>This is the API routes-</p>
<pre><code>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;
},
}
})

</code></pre>

<pre><code>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);
}
}
</code></pre>
<p>Now what I'm having a issue with is the uploading to a specific folder
even after verifying my accessToken to make sure its working properly and using 'parents={folderId} its still not following the upload location, though it still upload but only on the default location (My Drive), I just can't understand it properly. I would appreciate if anyone can explain to me and help me understand here.</p>
<p>The code is from
<a href="
" rel="nofollow noreferrer">
</a></p>
 

Latest posts

Top