I'm getting a PDF file from an external web resource using ajax. I want to store this PDF in the google drive using google script API from within google docs.
Sample of that ajax call:
$.ajax({
url: "<fancyurl>",
contentType: 'application/octet-stream',
responsetype: 'blob',
type: 'GET',
success: function(response) {
// or converted response.. etc..
google.script.run.withSuccessHandler(yay).withUserObject(this).createFile(response);
});
The response from the webresource is an octet-stream:
I've tried to import the original response, the response converted to blob, a uint8 blob and the base64string. All end up in errors or corrupt files.
var blob = Utilities.newBlob(data, 'application/pdf' ,'asdf.pdf');
// blob.setName('asdf.pdf');
// blob.setContentTypeFromExtension();
DriveApp.createFile(blob);
Where data is the response or converted response.
Does anybody know how to solve this or what google script expects as a valid input?
CodePudding user response:
In my experience, when the binary data is retrieved using ajax, the binary data is converted to the text data. By this, I'm worried that responsetype
of blob
and arraybuffer
might not be able to be used. I thought that this might be the reason of your issue. So, in this answer, I would like to propose using "XMLHttpRequest" instead of "ajax".
The modified script is as follows.
Modified script:
From:
$.ajax({
url: "<fancyurl>",
contentType: 'application/octet-stream',
responsetype: 'blob',
type: 'GET',
success: function(response) {
// or converted response.. etc..
google.script.run.withSuccessHandler(yay).withUserObject(this).createFile(response);
});
To:
const xhr = new XMLHttpRequest();
xhr.open('GET', "<fancyurl>", true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
google.script.run.withSuccessHandler(yay).withUserObject(this).createFile([...new Int8Array(this.response)]);
};
xhr.send();
In this modification, the binary data is converted to the array buffer and converted it to int8 array. By this, this data can be used as the byte array with Google Apps Script.
In this case, although I cannot see your whole script of Google Apps Script, you can use your Google Apps Script as follows.
function createFile(data) {
var blob = Utilities.newBlob(data, 'application/pdf', 'asdf.pdf');
DriveApp.createFile(blob);
}