#StackBounty: #javascript #google-api #gapi How to upload files to Google drive using gapi and resumable uploads?

Bounty: 50

I’m trying to follow this guide for doing resumable uploads on Google Drive through Google Api’s.

This is my code, you can see it makes 2 requests as the guide asks to, the first part creates the metadata, and then we use the location for starting uploading the files with the session created by the first request.

        const file = new File(['Hello, world!'], 'hello world.txt', { type: 'text/plain;charset=utf-8' });
        const contentType = file.type || 'application/octet-stream';

        const reqMetadata = gapi.client.request({
            'path': 'upload/drive/v3/files',
            'method': 'POST',
            'params': { 'uploadType': 'resumable' },
            'headers': {
                'X-Upload-Content-Type': file.type,
                'X-Upload-Content-Length': file.size,
                'Content-Type': 'application/json; charset=UTF-8'
            },
            'body': {
                'name': file.name,
                'mimeType': contentType,
                'Content-Type': contentType,
                'Content-Length': file.size
            }
        });

        reqMetadata.execute((respMetadata, rawRespMetadata: any) => {
            const locationUrl = JSON.parse(rawRespMetadata).gapiRequest.data.headers.location;

            const reader = new FileReader();

            reader.onload = (e) => {
                const reqFile = gapi.client.request({
                    'path': locationUrl,
                    'method': 'PUT',
                    'headers': {
                        'Content-Type': file.type,
                        'Content-Length': file.size
                    },
                    'body': reader.result
                });

                reqFile.execute(respFile => {
                    console.log(respFile);
                });
            };

            reader.readAsArrayBuffer(file);
        });

What’s the problem?

Well, seems that the Google Api library does not like the File / byte array as body on their gapi.client.request and they’re truncating it away see image

What’s the correct way to pass the file? I tried both body: file and body: reader.result but same result

PS: gapi is already fully authenticated & initialized with auth2, I’m able to create files / directory.


Get this bounty!!!