Advanced Drive Service - get contents of text file

145 views
Skip to first unread message

Alan Wells

unread,
Jun 19, 2019, 4:55:08 PM6/19/19
to Google Apps Script Community
The advanced drive service returns a file resource which doesn't have the contents of the file.  Is there a way to get the contents out of a text file using advanced drive service.  Do you need to use the download url?

Or do I need to use files.export?

Quote:
Exports a Google Doc to the requested MIME type and returns the exported content.

Dimu Designs

unread,
Jun 19, 2019, 5:33:18 PM6/19/19
to google-apps-sc...@googlegroups.com
If I recall correctly its a two step process. First you retrieve the file metadata via Drive.Files.get (or some such) and then you look for the downloadUrl property in the JSON response. You should be able to pull in the file content via a subsequent UrlFetch using the provided download url.

Note that the Advanced Service API leverage Version 2.0 of the Drive API. If you're using Version 3 (not available as an Advanced Service when last I checked), you will need to reference the webContentLink property.

Tanaike

unread,
Jun 19, 2019, 10:51:18 PM6/19/19
to Google Apps Script Community
About "a way to get the contents out of a text file using advanced drive service", unfortunately, in the current stage, it cannot be achieved. If the file you want to retrieve the content is not Google Docs, you can do it using files.get with "alt=media". For example, when the following script is run,

var res = Drive.Files.get(fileId);

the metadata of file is retrieved. On the other hand, when the following script is run,

var res = Drive.Files.get(fileId, {alt: "media"});


Status 200 and the file content are returned. But this is shown as an error.

And also, about "Drive.Files.export(fileId, mimeType)", the returned value is "void".

From above situation, I think that in the current stage, the text file might not be able to be downloaded by Advanced Google Services. So when Drive API is required to be used, as a current workaround, the file is required to be downloaded using UrlFetchApp as mentioned by Dimu Designs's comment.

Faustino Rodriguez

unread,
Jun 20, 2019, 6:48:19 AM6/20/19
to Google Apps Script Community
As explained before the only way so far is the combination of UrlFetchApp.fetch and downloadUrl
The following function will return the file content of a text file

function getFileContent(fileId, mimeType) {
 
return UrlFetchApp.fetch( Drive.Files.get(fileId).downloadUrl, {
   
'contentType': mimeType,
   
'headers': {
     
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
   
}
 
}).getContentText();
}


On Wednesday, June 19, 2019 at 4:55:08 PM UTC-4, aj.addons wrote:
Reply all
Reply to author
Forward
0 new messages