我需要修改我的应用程序脚本Google附加项目,以下载在我们的服务器中生成的文件(需要认证)到本地机器。没有找到将该文件直接下载到本地计算机的方法。所以尝试先将它下载到驱动器中,然后将驱动器文件下载到本地机器中。
目前,我已经实现了将该文件下载到Google中,现在正在寻找将其下载到本地机器的方法。搜索使用驱动器api进行此操作的方法。但还没找到办法。
下载文件将采用以下格式。
.pdf,.epub,.jpg,.png,.zip,.mobi,.indd
找到此文章,但它仅用于下载文本内容。
这是我从服务器检索文件的代码,下载到驱动器。
function downloadOutput(selectedFile){
var mimeType;
var template = new Template();
var documentProperties = PropertiesService.getDocumentProperties();
var jobFolderPath = replaceWhiteSpace(documentProperties.getProperty('JOB_FOLDER_PATH'));
var pathParts = jobFolderPath.split("/");
var outputFolderName = pathParts.pop();
var rootFolderID = getWriterRootFolder();
var filename = replaceWhiteSpace(selectedFile);
if (selectedFile.includes('.pdf')){
mimeType = 'application/pdf';
}
else if(selectedFile.includes('.epub')){
mimeType = 'application/epub+zip';
}
else if (selectedFile.includes('.jpg')){
mimeType = 'image/jpeg';
}
else if(selectedFile.includes('.png')){
mimeType = 'image/png';
}
else if(selectedFile.includes('.zip')){
mimeType= 'application/zip';
}
else if(selectedFile.includes('.mobi')){
mimeType= 'application/x-mobipocket-ebook';
}
else if(selectedFile.includes('.indd')){
mimeType = 'application/x-indesign';
}
//This is for retrieving the selectedFile from our server.
var response = sendRequest(template.server, template.customer, "/api/v2/","GET", "files" + jobFolderPath + "/"+ filename);
var output = {
title: selectedFile,
parents: [{'id':rootFolderID}],
mimeType: mimeType
};
var outputFile = Drive.Files.insert(output, response.getBlob());
//some tries to get a download from the drive file, but not worked.
var url = "https://www.googleapis.com/drive/v3/files/" + outputFile.id + "?alt=media&mimeType="+ mimeType;
var blob = UrlFetchApp.fetch(url, {
method: "get",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
});
var rrr = UrlFetchApp.fetch(outputFile.downloadUrl,
{
method :"get",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken() }
});
}
请建议将驱动器文件下载到本地计算机中的“下载”文件夹,或者直接将服务器文件下载到本地计算机,而不将其保存在驱动器中。
提前谢谢。
发布于 2022-04-19 12:21:28
只要应用程序脚本是服务器端执行,就没有直接的方式使用它来下载到您的机器。
但是,当您的文件在您的驱动器中时,使用Google的客户库之一(在您的例子中是驱动API )直接将其下载到您的机器上怎么样?
这些步骤很简单,查找文件,获取ID并下载到您的机器。
谷歌有关于下载文件的具体指南,包括从Google下载一个通用文件和下载文档,以及搜索特定文件,通过name = my_server_side_generated_file
或mimeType = 'application/epub+zip'
,或者任何你想使用的查询方法。
这是在Node.js中下载文件的简单用例,但是您也有关于Python的示例。
var fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
var dest = fs.createWriteStream('/tmp/photo.jpg');
drive.files.get({
fileId: fileId,
alt: 'media'
})
.on('end', function () {
console.log('Done');
})
.on('error', function (err) {
console.log('Error during download', err);
})
.pipe(dest);
文档:
https://stackoverflow.com/questions/71923837
复制相似问题