Get external URL and save to Drive - google-apps-script

I want to take a PDF URL and save it to Drive. The folder ID and URL are correct.
function uploadDoc(){
var folder = DriveApp.getFolderById('my_folder_id');
var url = 'my_url';
var blob = UrlFetchApp.fetch(url);
var blob2 = blob.getAs('appl‌​ication/pdf');
var newFile = folder.createFile('filename.pdf',blob2);
}
When I run this, I get:
Exception: Converting from binary/octet-stream to appl‌​ication/pdf is not supported.

You'll need to fix two things:
After UrlFetchApp.fetch(url) you need to use the getBlob() method. The getAs('appl‌​ication/pdf') method is not strictly required.
If you are using a blob, then you need to use the createFile(blob) method.
You are using the createFile(name, content) method and in this method, content is string not blob.
Then to name of the new file, you'll need the setName(name) method.
function uploadDoc() {
var url = 'https://www.gstatic.com/covid19/mobility/2021-02-21_AF_Mobility_Report_en.pdf';
var foID = 'my_folder_id';
var folder = DriveApp.getFolderById(foID);
var blob = UrlFetchApp.fetch(url).getBlob();
var newFile = folder.createFile(blob).setName('filename.pdf');
}

Related

how to parse (this) xml using Google Script

I need to parse this xml by Google Script. jsonformatter.org tells me that the XML is valid
I want to get text of ICO but //var ico = root.getChild('Ares_odpovedi').getChild('Odpoved').getChild('VBAS').getChild('ICO').getText(); is throwing an error
The full code is
function getARES() {
var url = 'https://wwwinfo.mfcr.cz/cgi-bin/ares/darv_bas.cgi?'
+ 'ico=06018025'
+ '&xml=1';
var response = UrlFetchApp.fetch(url);
var responseText = response.getContentText(); //.replace(/D:/g,'');
var document = XmlService.parse(responseText);
var root = document.getRootElement();
var ico_tmp0 = root.getName(); // value is "Ares_odpovedi"
var ico_tmp1 = root.getContentSize(); // value is 3
var ico_tmp2 = root.getChild('Ares_odpovedi'); // value is null
var ico_tmp3 = root.getChild('Odpoved'); // value is null
//var ico = root.getChild('Ares_odpovedi').getChild('Odpoved').getChild('VBAS').getChild('ICO').getText();
//var ico = root.getChild('Odpoved').getChild('VBAS').getChild('ICO').getText();
Logger.log(response);
Logger.log(" ");
Logger.log(responseText);
}
I believe your goal as follows.
You want to retrieve the text of ICO using Google Apps Script.
In this case, it is required to use the name space when getChild is used. When this is reflected to your script, it becomes as follows.
Modified script:
function getARES() {
var url = 'https://wwwinfo.mfcr.cz/cgi-bin/ares/darv_bas.cgi?'
+ 'ico=06018025'
+ '&xml=1';
var response = UrlFetchApp.fetch(url);
var responseText = response.getContentText(); //.replace(/D:/g,'');
var document = XmlService.parse(responseText);
var root = document.getRootElement();
// I modified below script.
var ns1 = XmlService.getNamespace("/ares/xml_doc/schemas/ares/ares_answer_basic/v_1.0.3");
var ns2 = XmlService.getNamespace("/ares/xml_doc/schemas/ares/ares_datatypes/v_1.0.3");
var res = root.getChild("Odpoved", ns1).getChild("VBAS", ns2).getChild("ICO", ns2).getText();
Logger.log(res)
}
When above script is run, 06018025 is retrieved.
When http://wwwinfo.mfcr.cz/cgi-bin/ares/darv_bas.cgi?ico=27074358&xml=1 is used as the URL of UrlFetchApp.fetch, 27074358 is obtained.
References:
XML Service
Added:
From your replying of Any idea why var res2 = root.getChild("Odpoved", ns1).getChild("VBAS", ns2).getChild("DIC", ns2).getText(); does not work?, now I noticed that your question had been changed.
In your question, you wanted to retrieve the value of ICO. But in the case for retrieving the value of DIC, it is required to check the structure of XML. Because in your script in your question, the XML from var url = 'https://wwwinfo.mfcr.cz/cgi-bin/ares/darv_bas.cgi?' + 'ico=06018025' + '&xml=1'; doesn't include the value of DIC. I think that this is the reason of your issue.
When you want to retrieve the value of DIC from http://wwwinfo.mfcr.cz/cgi-bin/ares/darv_bas.cgi?ico=27074358&xml=1, please use the following script.
Modified script:
function getARES() {
var url = 'http://wwwinfo.mfcr.cz/cgi-bin/ares/darv_bas.cgi?ico=27074358&xml=1'; // <--- Modified
var response = UrlFetchApp.fetch(url);
var responseText = response.getContentText(); //.replace(/D:/g,'');
var document = XmlService.parse(responseText);
var root = document.getRootElement();
var ns1 = XmlService.getNamespace("/ares/xml_doc/schemas/ares/ares_answer_basic/v_1.0.3");
var ns2 = XmlService.getNamespace("/ares/xml_doc/schemas/ares/ares_datatypes/v_1.0.3");
var res = root.getChild("Odpoved", ns1).getChild("VBAS", ns2).getChild("DIC", ns2).getText(); // <--- Modified
Logger.log(res) // In this case, CZ27074358 is retrieved.
}
Note:
About the name space, these threads might be useful.
What are XML namespaces for?
How does XPath deal with XML namespaces?

Fetch file from external URL and upload to Google Drive using Apps Script

I'm not sure if this is even possible. I'm trying to fetch file that being uploaded to formfacade server via the add-on in google form. I'm using it to allow other non-gmail users to upload file without having to sign-in.
I referred to answer from Mogsdad and dheeraj raj in
Can I download file from URL link generated by google apps script to use UrlFetchApp to meet this objective. Below are my codes:
Method 1 :
function UrlFile2gdrive() {
var sheet=SpreadsheetApp.getActiveSheet();
var lrow=sheet.getLastRow();
//var fileURL=sheet.getRange(lrow,2).getValue();
var fileURL='https://formfacade.com/uploaded/1FAIpQLSfscYq_sbYcT2P3Sj3AvSD2zYKalIM0SKdPTESf1wE9Rq8qew/'
+'97dc1ee0-f212-11ea-95c3-bdb6c5ab13b3/2124651919/A%20Sample%20PDF.pdf'
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var response=UrlFetchApp.fetch(fileURL,params);
Logger.log(response.getContentText());
var fileBlob=response.getBlob();
var folder='0B2b-M7h6xF-Mflk3dGswano2TnJ3dGlmZG8wOUREMFg4blM5SHBuM3lqYmdPOThZSTBTSWs'
var filename=fileURL.split("/").pop();
//var filename=fileURL.split("%2F").pop();
var file=decodeURIComponent(filename);
Logger.log("filename : "+file);
var newfile=DriveApp.getFolderById(folder).createFile(fileBlob.setName(file));
//var newfile=DriveApp.getFolderById(folder).createFile(response.setName(filename));
}
Method 2
//api-key : AIzaSyCcbdBCI-Kgcz3tE1N4paeF9a-vdi3Uzz8
//Declare function
function URL2gdriveWithPswd() {
//Getting url,existing name and new name for image from the sheet in
//variable url, name and new_name respectively
var sh = SpreadsheetApp.getActiveSheet();
var row = sh.getLastRow();
Logger.log(row);
//for (var i = 2; i <= row; i++) {
/*var url = sh.getRange(i, 2).getValue();
Logger.log(url);
var name = sh.getRange(i, 3).getValue();
var new_name = sh.getRange(i, 4).getValue();*/
var url = sh.getRange(row, 2).getValue();
Logger.log(url);
var filenm=url.split("/").pop();
var new_name=decodeURIComponent(filenm);
var name = sh.getRange(row, 3).getValue();
//var new_name = sh.getRange(row, 4).getValue();
//Creating authentication token for downloading image, it may not be //required if image can be downloaded without login into
var user = "dtestsys#gmail.com";
var password = "1851235656";
var headers = {
"Accept": "application/xml",
"Content-Type": "application/xml",
"Authorization": "Basic " + Utilities.base64Encode(user + ":" + password)
};
//defining method to download file
var options = {
"method": "get",
"headers": headers
};
//Getting folder name where to store downloaded image
var folders = DriveApp.getFoldersByName('File Uploader (File responses)');
while (folders.hasNext()) {
var folder = folders.next();
Logger.log(folder.getName());
}
//Getting response on hit of url using downloading method defined //earlier storing in Blob
var response = UrlFetchApp.fetch(url, options).getBlob();
//Creating image in folder defined with response in blob and logging same file //in log to check, if required
var file = folder.createFile(response);
Logger.log(file);
//renaming image
var images = folder.getFiles();
while (images.hasNext()) {
var image = images.next();
file.setName(new_name);
Logger.log("imagename : "+image.getName());
}
//}
}
However, both methods managed to get a file into my gdrive but the content consists of the html codes only (https://drive.google.com/file/d/1NYQoMmCQEoP3z6L8niq1mpvIx7xl83zu/view?usp=sharing), which I think the URL passed in google response sheet is just a "mask". I noticed that inside the file has some lines that mentioned api-key and code (next to user email address). Is it possible to achieve my objective? Are those api-key and code would be useful to get authorized to access the file and download it in gdrive?
I rechecked.The link produced and passed into my google sheet response is only the login page that redirects to another XML file. When I copied back the final URL after the original file content is displayed, the URL is as below:
https://storage.googleapis.com/formfacade-public/1FAIpQLSfscYq_sbYcT2P3Sj3AvSD2zYKalIM0SKdPTESf1wE9Rq8qew%2F97dc1ee0-f212-11ea-95c3-bdb6c5ab13b3%2F2124651919%2FA%20Sample%20PDF.pdf?GoogleAccessId=firebase-adminsdk-pve0p%40formfacade.iam.gserviceaccount.com&Expires=1599671507&Signature=fBzWej0fEgF6Aw7oCHX%2FTTUfHbcep%2Bj%2B%2FhB3fYFUDeq0SFTuyJ6jTnLWQJmldD6XkVug0%2BNki7ZPNo2ESufvIfQjhVLKXgvp7UiQheJ4GYL%2BtXgFLaUyglgemmfp7KSvIvPxpMcpC2lR8em3E5YIvMRr9tcfzagvusQYHEb9mlD7k833bVoqFUVWuP%2FkP8tl%2BHYVL15kSXAjtFif4QZpu%2FFHwSik89Keo78LKTm0U8hZiAMeYDQZWF6w1pcKpy04md3xKtDPwZYCoUWOOtKkCI6JLskE5HweDvMCGnDbxW8o6SWD%2BIC%2FlaNC6%2BJ81OB10cuRqwQPEc9LnfgCZK7b1A%3D%3D
When I pasted the above link, I got to see as per screenshot below:-
. So, I'm guessing they don't share direct access link to the uploaded file so that we are left with the option to buy/subscribe the paid version.
Would anyone knows if there's any better altrnative(s) I could use to achieve this objective? Like maybe a link with API-key just like what I learnt from #Tanaike in his previous answer on Convert-API to convert pdf file to PNG? Of course it has some limits for the free version but it still is a very helpful solution.
You are not assigning content-type of the blob anywhere. But if you do the naming right it would not matter. In method 1 you are trying to set a name on the blob when you should be setting it on the file created from the Blob.
Try setting the name on the file after creating it.
Example:
function myFunction() {
var url ="http://www.africau.edu/images/default/sample.pdf";
var response = UrlFetchApp.fetch(url);
console.log(response.getResponseCode());
var blob=response.getAs('application/pdf');
var folder = "<SOME-FOLDER-ID>";
var fileName=decodeURIComponent(url.split("/").pop());
console.log("File named : "+fileName);
var file=DriveApp.getFolderById(folder).createFile(blob);
// Set the name to the created file after creating it!
file.setName(fileName);
}
For reference see class File.

Downloading a Google Slides presentation as PowerPoint doc using Google Apps Script?

The GUI of Google Slides offers to download a GSlides presentation as a Powerpoint (myFile.pptx). I could not find the equivalent in the Google Apps Script documentation - any pointer?
EDIT
Thanks to comments and answers, I tried this snippet:
function testFileOps() {
// Converts the file named 'Synthese' (which happens to be a Google Slide doc) into a pptx
var files = DriveApp.getFilesByName('Synthese');
var rootFolder = DriveApp.getRootFolder();
while (files.hasNext()) {
var file = files.next();
var blobPptx = file.getBlob().getAs('application/vnd.openxmlformats-officedocument.presentationml.presentation');
var result = rootFolder.createFile(blobPptx);
}
}
It returns an error:
Converting from application/vnd.google-apps.presentation to
application/vnd.openxmlformats-officedocument.presentationml.presentation
is not supported. (line 7, file "Code")
SECOND EDIT
As per another suggestion in comments, I tried to make an http call from Google App Script, that would directly convert the gslides into pptx, without size limit. It produces a file on G Drive, but this file is corrupted / unreadable. The GAS script:
function convertFileToPptx() {
// Converts a public Google Slide file into a pptx
var rootFolder = DriveApp.getRootFolder();
var response = UrlFetchApp.fetch('https://docs.google.com/presentation/d/1Zc4-yFoUYONXSLleV_IaFRlNk6flRKUuAw8M36VZe-4/export/pptx');
var blobPptx = response.getContent();
var result = rootFolder.createFile('test2.pptx',blobPptx,MimeType.MICROSOFT_POWERPOINT);
}
Notes:
I got the mime type for pptx here
using the mime type 'pptx' returns the same error message
How about this modification?
Modification point:
response.getContent() returns byte array. So please use response.getBlob().
Modified script:
function convertFileToPptx() {
var fileId = "1Zc4-yFoUYONXSLleV_IaFRlNk6flRKUuAw8M36VZe-4";
var outputFileName = "test2.pptx";
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx';
var rootFolder = DriveApp.getRootFolder();
var response = UrlFetchApp.fetch(url);
var blobPptx = response.getBlob();
var result = rootFolder.createFile(blobPptx.setName(outputFileName));
}
Note:
If you want to convert Google Slides, which are not published, in your Google Drive, please use access token. At that time please modify url as follows.
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx?access_token=' + ScriptApp.getOAuthToken();
DriveApp.createFile() creates a file on root folder as the default.
References:
Class HTTPResponse
getOAuthToken()
As mentioned by tehhowch, you could get the Google Slide file from your Drive and get it as a .pptx. (Not sure of mime type.)
File#getAs:
I add all modifications with token part and specific folder
function convertFileToPptx() {
var fileId = "Your File ID";
var outputFileName = "name.pptx";
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx';
//var rootFolder = DriveApp.getRootFolder();
var rootFolder = DriveApp.getFolderById("Your Folder ID")
var params = {method:"GET", headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url,params);
var blobPptx = response.getBlob();
var result = rootFolder.createFile(blobPptx.setName(outputFileName));
}
To get the byte[] do:
function downloadAsPPTX(){
var presentation = SlidesApp.getActivePresentation();
var fileId = presentation.getId();
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx';
var response = UrlFetchApp.fetch(url);
var blobPptx = response.getBlob();
Logger.log("size: "+blobPptx.getBytes().length);
}

Get file ID by its folder and name

I'm copying a specific file to a specific folder, here's the code:
var fileID = "123abc";
var folderID = "abc123";
var name = "Conferencia " + Utilities.formatDate(source.getRange(2,4).getValue(), "GMT", "dd-MM-yyyy");
var file = DriveApp.getFileById(fileID);
var folder = DriveApp.getFolderById(folderID);
var newFile = file.makeCopy(name,folder);
var newUrl = DocumentApp.openById(newFile.getId());
Logger.log(newUrl);
This code works perfectly, except by the var newUrl = DocumentApp.openById(newFile.getId());. This line should record the ID of the new file but it won't work.
How to make it work?
var newUrl = DocumentApp.openById(newFile.getId());
means that newUrl is now a Document object, pointing to your Google Document contained in that file (presumably it's a Google Document file, otherwise there's an error already). It's not an Id or URL or a string of any sort.
If you want to get the URL of the file, use the getUrl method:
var newUrl = newFile.getUrl();
If you want to get the Id (which is just the last part of the URL), then it's
var newId = newFile.getId();
These are strings which can later be used in DocumentApp.openByUrl or DocumentApp.openById if you want to use them; these methods will return a Document object.

Can I download file from URL link generated by google apps script

Please help I'm learning google-apps-script for short time.
I want to download file from remote site by url generating from data that stores in my spreadsheet.
for example, i have 2 paremeters:
Cell1 = val1, val2, ... valN
Cell2 = val21, val22, ... val2N
I split string from cell data to Arrays and than generate URL. for example: http://mysite.com/files/file.val1.val22.zip
Than i need to download file from this link...
Can I do this process automaticaly ?
This example function will retrieve your zip file, and place it into your Google Drive in folder "StackOverflow". You can also download a more complete version from this gist.
function getFile(fileURL) {
// see https://developers.google.com/apps-script/class_urlfetchapp
var response = UrlFetchApp.fetch(fileURL);
var fileBlob = response.getBlob()
var folder = DocsList.getFolder('StackOverflow');
var result = folder.createFile(fileBlob);
debugger; // Stop to observe if in debugger
}
For example:
getFile( "http://mysite.com/files/file.val1.val22.zip" );
Note that you cannot download per se, since you have no access to your PC's resources (e.g. file system) from apps-script. The file is still in "the cloud"... in this case, it's been copied from the web site it was on, into Google Drive. If you're running the Drive app, though, the file will now sync to your PC.
Yes, You can.
Hope below code can solve your problem:
//Declare function
function downloadFile() {
//Getting url,existing name and new name for image from the sheet in
//variable url, name and new_name respectively
var sh = SpreadsheetApp.getActiveSheet();
var row = sh.getLastRow();
Logger.log(row);
for (var i = 2; i <= row; i++) {
var url = sh.getRange(i, 10).getValue();
Logger.log(url);
var name = sh.getRange(i, 13).getValue();
var new_name = sh.getRange(i, 4).getValue();
//Creating authentication token for downloading image, it may not be //required if image can be downloaded without login into
var user = "***************";
var password = "************";
var headers = {
"Accept": "application/xml",
"Content-Type": "application/xml",
"Authorization": "Basic " + Utilities.base64Encode(user + ":" + password)
};
//defining method to download file
var options = {
"method": "get",
"headers": headers
};
//Getting folder name where to store downloaded image
var folders = DriveApp.getFoldersByName('test');
while (folders.hasNext()) {
var folder = folders.next();
Logger.log(folder.getName());
}
//Getting response on hit of url using downloading method defined //earlier storing in Blob
var response = UrlFetchApp.fetch(url, options).getBlob();
//Creating image in folder defined with response in blob and logging same file //in log to check, if required
var file = folder.createFile(response);
Logger.log(file);
//renaming image
var images = folder.getFiles();
while (images.hasNext()) {
var image = images.next();
file.setName(new_name);
Logger.log(image.getName());
}
}
}
//Hope you get it now
It's worked for me.
function downloadFile() {
var url = "https://raw.githubusercontent.com/hoat23/VisionArtificialAndImageProcessing/master/bin/utils_imgprocessing.py"
Logger.log(url);
var response = UrlFetchApp.fetch(url);
var text = response.getContentText()
var newFile = DriveApp.createFile('testfilegoogle.txt',text);
debugger; // Stop to observe if in debugger
}
//Hope you get it now