How can I upload a file on google drive using google api with javascript?

Viewed 38

I have a chat application in which I wanted to use google drive for storing any file shared with conversation. I had done this using php but now I wanted to do this thing on client side using javascript. I already have the access and refresh token stored in my database, now I just wanted to upload any media files using that token.

const uploadImg = async()=>{
        let gtoken = <my access and refresh token>
        const fileMetadata = {
            name: fileData.name,
            parents: []  
        }
        const form = new FormData();
        form.append('metadata', new Blob([JSON.stringify(fileMetadata)], {type: 'application/json'}));
        form.append('file', new Blob([new Uint8Array(fileData.data)], {type: fileData.type}));
        fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {
            method: 'POST',
            headers: new Headers({'Authorization': 'Bearer ' + gtoken.access_token}),
            body: form
        }).then(res => res.json()).then(res => console.log(res)); 
    }

I am using this method but getting error 401(unauthenticated).

0 Answers
Related