请帮助我在短时间内学习google-apps-script。 我想通过url从我的电子表格中存储的数据生成来从远程站点下载文件。
例如,我有2个参数:
Cell1 = val1, val2, ... valN
Cell2 = val21, val22, ... val2N
我将字符串从单元格数据拆分为数组,然后生成URL。例如:http://mysite.com/files/file.val1.val22.zip
我需要从这个链接下载文件...
我可以自动执行此过程吗?
答案 0 :(得分:3)
此示例功能将检索您的zip文件,并将其放入Google云端硬盘“StackOverflow”文件夹中。您还可以从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
}
例如:
getFile( "http://mysite.com/files/file.val1.val22.zip" );
请注意,您无法下载本身,因为您无法从应用程序脚本访问您的PC资源(例如文件系统)。该文件仍处于“云端”......在这种情况下,它已从其所在的网站复制到Google云端硬盘中。但是,如果您正在运行云端硬盘应用,该文件现在将同步到您的PC。
答案 1 :(得分:0)
是的,你可以。
希望下面的代码可以解决您的问题:
//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
答案 2 :(得分:0)
对我有用。
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