Skip to content Skip to sidebar Skip to footer

Send Post Request On Google Api Using Javascript On Browser

I am getting 404 error on my $.ajax request in Google API. I have these codes, var asyncLoad = require('react-async-loader'); var CLIENT_ID = ''; var DISCOVERY_DOCS

Solution 1:

The 404 error is caused because the url is missing the files part: https://www.googleapis.com/upload/drive/v3/files?uploadType=media. See Google Drive APIs > REST - Files: create.

I managed to upload an image that was read from <input type="file" accept="image/*"> with FileReader.readAsDataURL() method as follows:

var metadata = {
    name: 'image.jpg',
    mimeType: 'image/jpeg'
}

var user = gapi.auth2.getAuthInstance().currentUser.get();
var oauthToken = user.getAuthResponse(true).access_token;

var boundary = 'foo_bar_baz';
vardata = '--' + boundary + '\n';
data += 'content-type: application/json; charset=UTF-8' + '\n\n';
data += JSON.stringify(metadata) + '\n';
data += '--' + boundary + '\n';

var dataURL = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAZAAA/+EKhWh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8APD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZ...'var dataURLparts = dataURL.split(',', 2);
var dataURLheaderParts = dataURLparts[0].split(':');
var dataURLheaderPayloadParts = dataURLheaderParts[1].split(';');

data += 'content-transfer-encoding: ' + dataURLheaderPayloadParts[1] + '\n';
data += 'content-type: ' + dataURLheaderPayloadParts[0] + '\n\n';
data += dataURLparts[1] + '\n';
data += '--' + boundary + '--';

$.ajax({
    type: 'POST',
    url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + oauthToken);
     },
     contentType: 'multipart/related; boundary=' + boundary,
     data: data,
     processData: false
 }).done(function(response) {
     console.log(response);
 });

Solution 2:

After many hours of hair pulling and viewing the same answers. The only thing that worked for me was to change from the multipart request (that Google documents) to using FormData.

Credit to this answer.

While the data arrived to Drive (successful upload), it wasnt processed correctly so image or PDF were not viewable and downloading it showed it was saved in base64.

const metadata = JSON.stringify({
  name: myFile.name,
  mimeType: myFile.type,
});

const requestData = newFormData();

requestData.append("metadata", newBlob([metadata], {
  type: "application/json"
}));

requestData.append("file", items[0].file);

const xhr = newXMLHttpRequest();

xhr.open("POST", "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart");

const token = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().access_token;

xhr.setRequestHeader("Authorization", `Bearer ${token}`);

xhr.send(requestData);

Post a Comment for "Send Post Request On Google Api Using Javascript On Browser"