我正在尝试编写Google Apps脚本来下载特定云端硬盘文件夹中的所有文件(可能是.csv文件)。我找到了getDownloadUrl()方法,但我无法弄清楚用它做什么做。我目前正在尝试以下代码,其中files
是文件夹中文件的列表:
while(files.hasNext()) {
var response = UrlFetchApp.fetch(files.next().getDownloadUrl());
Logger.log(response.getContentText());
}
但是,当我尝试运行代码时,我收到401错误,我想这意味着我没有正确的授权?但我的印象是,如果所有内容都发生在我的一个Google帐户中,我就不需要完成所有OAuth2步骤。 The Google guide to connecting to external APIs看起来我应该只能抓取网址。我已经可以访问我的Drive文件了,因为当我运行该方法时,下载URL确实存在。我在这里错过了什么?我对这一切都很陌生,所以也许这是基本的东西。
谢谢!
修改 我设法通过修改代码修复401错误,如下所示:
while(files.hasNext()) {
var response = UrlFetchApp.fetch(files.next().getDownloadUrl(),{headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});
Logger.log(response.getContentText());
}
但问题仍然是这只会将内容返回给我,而不是下载文件。如何从此fetch
电话的结果中启动下载?
答案 0 :(得分:1)
除了列出所有下载链接之外,我想原始的发帖人也希望将文件下载到用户的计算机上(根据早期的discussion)。
为此,请在服务器端使用base 64编码blob(例如Google App Script),然后在客户端的浏览器中使用数据URI下载。下面是在this answer的帮助下的代码。
Google App脚本
...
function getBlobInBase64(fileId){
// omit authorization code if any
var file = DriveApp.getFileById(fileId);
var blob = file .getBlob();
return {
file_name: file.getName(),
mime: file.getMimeType(),
b64: Utilities.base64Encode(blob.getBytes());
}
...
与index.html
一起使用的Javascript
...
function getFile(fileId){
google.script.run.withSuccessHandler((data) => {
var uri = 'data:' + data.mime + ';charset=ISO-8859-1;base64,' + encodeURIComponent(data.b64);
downloadURI(uri, data.file_name);
}).withFailureHandler((err) => {
console.log(err);
}).getBlobInBase64();
}
...
注意:我没有运行此代码,但是该方法应该可以在其他项目中使用。
答案 1 :(得分:0)
这将记录文件名和&可供下载的任何文件的URLS(根驱动器中的前100个):
function myFunction() {
var files = DriveApp.getFiles();
var c = 0;
while (files.hasNext() && c<100) {
var file = files.next();
Logger.log("File Name: " + file.getName());
Logger.log(" Download URL: " + file.getDownloadUrl());
c++;
}
}
答案 2 :(得分:0)
我的回答可能有些偏差,但我认为您有更好的机会从Google云端硬盘using the webContentLink下载文件,因为这是我常用的方法。我使用Files.list获取webContentLink,并在fields参数中请求webContentLink。我通过浏览器运行该链接并下载文件。
答案 3 :(得分:0)
If you are trying to download Google Drive files to local computer using Google Apps Script, Then please understand that Google Apps Script is a server side scripting language. It can't download and save files to your local drive.
答案 4 :(得分:0)
这是一个可能对您有所帮助的网络应用程序。它并不完全符合您的要求,但您可以编辑它并获得结果。希望它有所帮助!
CODE:
function doGet(e) { // main function
var template = HtmlService.createTemplateFromFile('index.html'); // filename always!
return template.evaluate().setTitle('Search Drive').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
// Process the form
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm); // Call to the search files function to search files on google drive
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn; // return the results
}
function SearchFiles(searchTerm) {
var searchFor ="title contains '" + searchTerm + "'"; //single quotes are needed around searchterm
var owneris ="and 'YOUREmail@email.com' in Owners"; //email address to search for
var names = [];
Logger.log(searchFor + " " + owneris);
var files = DriveApp.searchFiles(searchFor + " " + owneris);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
var lm = file.getLastUpdated();
var name = file.getName()+"|~|"+fileId+"|~|"+lm; // Im concatenating the filename with file id separated by |~|
names.push(name); // adding to the array
}
return names; // return results
}
&#13;
的index.html
<html>
<head>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
// Below call means: call to processForm passing the searchTerm value (previously escaped) and after finish call the handleResults function
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
console.log('Handle Results was called! ');
document.writeln('<a href="http://LINKBACKTOYOURSCRIPT">BACK</a><br/><br/>');
var length=results.length; // total elements of results
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|"); // split the line |~|, position 0 has the filename and 1 the file id
document.writeln("<b><a href='https://docs.google.com/document/d/"+item[1]+"' target='_blank'>"+item[0]+"</b></a> (Last modified: "+item[2]+")<br/><br/>"); // write result
}
document.writeln("End of results...");
}
</script>
</head>
<body><center><br/>
Search: <input type="text" id="idSrchTerm" name="search">
<input type="button" value="search files on Google Drive" name="submitButton" onclick="displayMessage()"/>
</center>
</body>
</html>
&#13;