DriveApp.createFile causes a server error - google-apps-script

I got the following error when I tried to download a picture from a URL using Google Apps Script.
We're sorry, a server error occurred. Please wait a bit and try again.
Here is the code.
function TT() {
var response = UrlFetchApp.fetch('https://www.dropbox.com/s/g9jtm390l67uqkb/128.png?dl=1');
var blob = response.getBlob();
Logger.log(blob.getContentType());
var file = DriveApp.createFile(response);
}

Well, should try to create a file from its blob, not from the response it self.
function TT() {
var response = UrlFetchApp.fetch('https://www.dropbox.com/s/g9jtm390l67uqkb/128.png?dl=1');
var blob = response.getBlob();
Logger.log(blob.getContentType());
var file = DriveApp.createFile(blob);
}
I'v runned a test and it works perfectly.

Related

I can´t upload documents to Google Sites from url using Apps Scripts

I am trying to upload files to Google Sites using the Url from my G-Drive. I am using this code, it is running but when I refresh the site the files don´t upload.
function uploadFiles(url, h) {
try {
var url = "myFileUrl";
var site = SitesApp.getSite("mySite", "myPage");
var page = site.getAllDescendants()[0];
var id = getIdFrom(url); // function that I have that gives you the id of an url
var blob = DriveApp.getFileById(id).getBlob();
var attachment = page.addHostedAttachment(blob);
return attachment.getUrl();
}
catch(error)
{
return error.toString();
}
There was no error when I ran it. I already solved this problem with a code bellow, but now I have a new one. When I upload the file it uploads as a .html file, and I want to upload it as .pptx or . xls depending on what type of document it is.
function uploadblob() {
var url = "myFileUrl;
var site = SitesApp.getSite("mySite", "myPage");
var page = site.getAllDescendants()[0];
var blob = UrlFetchApp.fetch(url).getBlob();
var attach = page.addHostedAttachment(blob);
}

'Invalid Argument' error with un-gzipping Blob in Apps script

I have a script that receives a gzipped blob from 3rd party API. I'm trying to un-gzip it using Utilities.ungzip() but getting an Invalid Argument error. Here's a sample code:
var liveReportResponse = UrlFetchApp.fetch(url)
var unzipped = Utilities.ungzip(liveReportResponse.getBlob()) // Fails with Invalid Argument error
An odd thing is that I can extract the content using the Drive File as intermediate storage:
var image = liveReportResponse.getBlob()
var file = {
title: 'some_file_.gzip'
};
file = Drive.Files.insert(file, image);
var file = DriveApp.getFileById(file.id)
var blob = file.getBlob()
var someBytes = Utilities.ungzip(blob) // It works
var data = someBytes.getDataAsString()
Would appreciate any help for fixing that.
Eventually, managed to fix that with:
liveReportResponse.getBlob().setContentType('application/x-gzip')
application/x-gzip seems not to be documented anywhere, but I've got it from blob.getContentType()

Google Script UrlFetchApp.fetch returns a 404 eventhough the page exist

I am sending automated report with Google spreadsheet and Google script.
So far it was working perfectly. But somehow when I try to create a new report to be emailed, the function "UrlFetchApp.fetch" return a 404. The same situation happened when I tried copying the old report.
The line with "UrlFetchApp.fetch" give me this error:
Request failed for https://docs.google.com/spreadsheets/d/1qm_bCKn4MbLKy7AIuIeu7bTZcTk8ObYBln0GAxwfsX8/pub?gid=195635557&single=true&output=pdf returned code 404. Truncated server response
It seems that I am not the only one having the issue but I cannot find any solution to it.
Here is the code:
function emailSpreadsheetAsCSV() {
var ss = SpreadsheetApp.openById("1qm_bCKn4MbLKy7AIuIeu7bTZcTk8ObYBln0GAxwfsX8");
var url = ss.getUrl();
url = url.replace(/edit$/,'');
var token = ScriptApp.getOAuthToken();
var sheets = ss.getSheets();
//make an empty array to hold your fetched blobs
var blobs = [];
for (var i=0; i<sheets.length; i++) {
var response = UrlFetchApp.fetch("https://docs.google.com/spreadsheets/d/1qm_bCKn4MbLKy7AIuIeu7bTZcTk8ObYBln0GAxwfsX8/pub?gid=195635557&single=true&output=pdf", {
headers: {
'Authorization': 'Bearer ' + token
},
'muteHttpExceptions': false
});
//convert the response to a blob and store in our array
blobs[i] = response.getBlob().setName(sheets[i].getName() + '.csv');
}
//create new blob that is a zip file containing our blob array
var zipBlob = Utilities.zip(blobs).setName(ss.getName() + '.zip');
return blobs[0];
}
Thanks a lot for your help.
Aymeric.
I've gotten this problem too and after some research, Spence Easton (question 34573295) solved my issue. I simply added this bogus call to drive so access is granted, and so the script can now get to your file.
Add this near the top before trying to grab the url:
var bogus = DriveApp.getRootFolder();
Now it runs fine with no 404 errors.
Remove the headers from the request:
var response = UrlFetchApp.fetch("https://docs.google.com/spreadsheets/d/1qm_bCKn4MbLKy7AIuIeu7bTZcTk8ObYBln0GAxwfsX8/pub?gid=195635557&single=true&output=pdf", {
'muteHttpExceptions': false
});
Check if it works for you.
You use the "pub" url so are you sure the spreadsheet is published on the web ? If you get a 404 it means the page is not published.
If file is published the bearer is not necessary as it is public now.
After I don't really understand your code because you iterate all the sheets of your file
for (var i=0; i<sheets.length; i++)
but the param "gid" (pub?gid=195635557&single=true&output=pdf) for the url in your urlfetch is fixed ?
Second point you get the file as pdf and after you create a csv ?
Why not get the file as csv directly : https://docs.google.com/spreadsheets/export?id=TheIdOfTheFile&exportFormat=csv
By adapting this code you can get the csv directly, see : https://stackoverflow.com/a/28503601/3556215
Take care you will get the first page and not others.
Stéphane
Try with:
var response = UrlFetchApp.fetch(url, options);
var result = JSON.parse(res.getContentText());

How To Call External API Using Google App Script via URLFetch Class

function checkACBalance() {
try{
var url ="http://sms.mydomain.com/api/balance.php";
alert(url);
var payload = {authkey:'d5558466554f11aa909d565ede677d40', route:'1'};
alert(payload);
var payload_json = encodeURIComponent(JSON.stringify(payload));
alert(payload_json);
var options = {method:"POST",contentType:"application/json",payload:payload_json,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
alert(response)
var res_code = result.getResponseCode();
alert(res_code)
}catch(e){
alert(e)
}
}
Now the problem is that when I am using this URLFetch Class for calling external API then this is not working.
In browser console an error has been shown:
Uncaught TypeError: Cannot read property 'fetch' of undefined
To build on what Kriggs is saying in the comments, it looks like you're trying to use UrlFetchApp.fetch in your .js file (the client). You want to make this call in your .gs file (the server).

Google Apps Scripts - MSWord to String

When I attempt to run the following code (Output will be XML):
function doGet(e){
return getFilesHtml();
}
function getFilesHtml() {
//Create second to top level XML parent
var xml = XmlService.createElement('response');
try{
var files = DriveApp.getFilesByName('ANNOUNCEMENTS.doc');
//Iterate through files and push to an array
var filesarray = new Array();
while(files.hasNext()) {
filesarray.push(files.next());
}
var file = getNewestFile(filesarray);
//Create necessary XML elements and information
var file_content = XmlService.createElement('content').setText(file.getBlob().getDataAsString('UTF-8'));
xml.addContent(file_content);
}catch(error){
var stat_child = XmlService.createElement('status').setText('failure');
var message_child = XmlService.createElement('message').setText(error.message);
xml.addContent(stat_child);
xml.addContent(message_child);
}
//Prepare and respond with XML
var document = XmlService.createDocument(xml);
var xml2 = XmlService.getPrettyFormat().format(document);
//Return the XML
return ContentService.createTextOutput(xml2).setMimeType(ContentService.MimeType.XML);
}
function getNewestFile(array){
array.sort(function(a,b){
return new Date(b.getDateCreated()) - new Date(a.getDateCreated());
});
return array[0];
}
I get the following failure response:
<response>
<status>failure</status>
<message>
We're sorry, a server error occurred. Please wait a bit and try again.
</message>
</response>
My ultimate goal is to get the contents of this file. I've tried .getAs('application/pdf'), but that works not, like this. Is there any other method or a method to correct this issue?
The error message "We're sorry, a server error occurred. Please wait a bit and try again." indicates that something went wrong deep within Apps Script. You'll have to troubleshoot the problem further before you can get help, and the Apps Script troubleshooting guide should help you do that.