Search code examples
javascriptgoogle-drive-apiclient-sidegoogle-api-js-client

Unwanted "content-type: text/plain;charset=UTF-8" header in Google Drive API Response


I am using the browser GAPI library to request a piece of binary data from Google Drive. The response from the google server always has a content-type: text/plain;charset=UTF-8 header, because of which, the browser always decoded the binary data into a UTF-8 character string.

What's more, the decoding process seems to add padding to the original binary data. For example, a 282-byte binary after UTF-8 decoding becomes 422-bytes long.

Is there any way to tell the Google API server to change the content-type header?

Or is there a way to bypass the preprocessing of the response body and get the raw response instead?

My code for requesting is listed here:

currentApiRequest = {
    path: `https://www.googleapis.com/drive/v3/files/${fileID}`,
    params: {
        alt: "media"
    }
}
gapi.client.request(currentApiRequest).then(
    (response) => {
                let data = response.body;
                console.log(byteSize(data));
                console.log(data);
    }
)

Solution

  • How about the following modification? In this modification, at first, the retrieved data is converted to Unit8Array and converted it to the blob.

    Modified script:

    const fileID = "###"; // Please set your file ID.
    currentApiRequest = {
      path: `https://www.googleapis.com/drive/v3/files/${fileID}`,
      params: {alt: "media"}
    };
    gapi.client.request(currentApiRequest)
    .then((response) => {
      let data = response.body;
      const blob = new Blob([new Uint8Array(data.length).map((_, i) => data.charCodeAt(i))]);
    
      // When you use the following script, you can confirm whether this blob can be used as the correct data.
      const filename = "sample.png"; // Please set the sample filename.
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.href = URL.createObjectURL(blob);
      a.download = filename;
      a.click();
    });
    

    References: