2
votes

I'm trying to upload data to a file using the Google Drive v3 API by making a XMLHttpRequest.

I get the id of a file using the File Picker API which returns "0BzAI5S8IJebrUnQtYWFSVzhPdVk", so that the upload URL should be "https://www.googleapis.com/upload/drive/v3/files/0BzAI5S8IJebrUnQtYWFSVzhPdVk?uploadType=resumable".

After I make the PUT request, it returns a 404 status code with "Not Found" as the responseText.

I've tried it before and it would return with status 200 and I was able to get the Location header from the response, but now I can't get a 200 status code from any file.

Here's my code:

// Log the user in using attachClickHandler (https://developers.google.com/identity/sign-in/web/reference#googleauthattachclickhandlercontainer-options--onsuccess-onfailure)

var id = "0BzAI5S8IJebrOFVMTU5Od183Q2M";
var access_token = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().access_token;

var xhr = new XMLHttpRequest();

xhr.open('PUT', 'https://www.googleapis.com/upload/drive/v3/files/' + id + '?uploadType=resumable');
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);

xhr.onreadystatechange = function() {
    if (this.readyState == 4) console.log(this.status);
};
xhr.send();

No matter which file I choose, it always outputs 404 as the status code. I follow what it says at https://developers.google.com/drive/v3/web/resumable-upload, but it mentions nothing of why you would receive a 404 response. Any help?

1
From the page you link, you are missing a couple of mandatory http headers. Otherwise, 404 would suggest there is a problem with the file ID you are using. Are you sure it's correct and is writeable by the logged in user?pinoyyid
They're definitely writable. I've tried with three different files on my own account that I own, so I can write to all three. Which other headers am I missing? The X-Content-Upload-Length/Type headers are optional and the Content-Type header is required only if I send metadata.ChristianFigueroa
The other was content-length. Not sure if it's the problem, just ruling out all possibilities. Try another operation on the ID such as a files.get, just to double check the ID.pinoyyid
File.get returns a 200 response with the proper information. It also works on the API Explorer on developers.google.com/drive/v3/reference/files/get so it can't be the ID.ChristianFigueroa
Also the browser doesn't let me change the Content-Length header. The browser sets the header automatically and throws an error if I try to change it manually: Refused to set unsafe header "Content-Length"ChristianFigueroa

1 Answers

7
votes

Turns out I was trying to do the wrong thing. I wanted to update a file, not upload one. Instead of using "PUT", I should've been using "PATCH" as explained here. This returned a 200 response with the Location header to make the actual change.