Reputation:
I had the upload file working with xmlhttprequest but I was using a Service Worker so I switched to using fetch.
I am getting a 401 error when sending my request but I know I have an access token.
function uploadFile() {
let accessToken = gapi.auth.getToken().access_token; // Google Drive API Access Token
let fileContent = document.querySelector('#content').value; // As a sample, upload a text file.
console.log('File Should Contain : ' + fileContent);
let file = new Blob([fileContent], { type: 'application/text' });
let metadata = {
name: 'Background', // Filename
mimeType: 'text/plain', // mimeType at Google Drive
parents: ['root'], // Folder ID in Google Drive
};
let form = new FormData();
form.append(
'metadata',
new Blob([JSON.stringify(metadata)], { type: 'application/json' })
);
form.append('file', file);
fetch(
'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id',
{
method: 'POST',
headers: new Headers({ Authorization: 'Bearer' + accessToken }),
body: form,
}
)
.then((res) => {
return res.json();
})
.then(function (val) {
console.log(val);
});
}
Anyone know what I am missing ?
Here is the error I am receiving back
error:
code: 401
errors: Array(1)
0: {domain: "global", reason: "authError", message: "Invalid Credentials", locationType: "header", location: "Authorization"}
length: 1
__proto__: Array(0)
message: "Invalid Credentials"
__proto__: Object
__proto__: Object
Upvotes: 1
Views: 173
Reputation: 201378
I think that the reason of your issue of Invalid Credentials
is headers: new Headers({ Authorization: 'Bearer' + accessToken }),
. Please modify as follows.
headers: new Headers({ Authorization: 'Bearer' + accessToken }),
headers: new Headers({ Authorization: 'Bearer ' + accessToken }),
before Bearer
like above.Upvotes: 1