简体   繁体   English

从外部 URL 获取文件并使用 Apps 脚本上传到 Google Drive

[英]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.我正在尝试通过 google 表单中的插件获取上传到 formfacade 服务器的文件。 I'm using it to allow other non-gmail users to upload file without having to sign-in.我正在使用它来允许其他非gmail用户上传文件而无需登录。

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.我参考了 Mogsdad 和 dheeraj raj 在我可以从谷歌应用程序脚本生成的 URL 链接下载文件以使用 UrlFetchApp 来实现这一目标的答案。 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".但是,这两种方法都设法将文件放入我的 gdrive 中,但内容仅包含 html 代码( https://drive.google.com/file/d/1NYQoMmCQEoP3z6L8niq1mpvIx7xl83zu/view?usp=sharing ),我认为是 URL在谷歌响应表中传递只是一个“面具”。 I noticed that inside the file has some lines that mentioned api-key and code (next to user email address).我注意到文件里面有一些提到 api-key 和 code 的行(在用户电子邮件地址旁边)。 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?这些 api-key 和代码对于获得授权访问文件并将其下载到 gdrive 中是否有用?

I rechecked.The link produced and passed into my google sheet response is only the login page that redirects to another XML file.我重新检查了。生成并传递到我的谷歌表响应的链接只是重定向到另一个 XML 文件的登录页面。 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当我在显示原始文件内容后复制回最终 URL 时,URL 如下: https ://storage.googleapis.com/formfacade-public/1FAIpQLSfscYq_sbYcT2P3Sj3AvSD2zYKalIM0SKdPTESf1wE9Rq8qew%2F97dc1ee0-f212-11ea-95c3-bdb6c5ab13b3%2F212466 %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:-当我粘贴上面的链接时,我看到了下面的截图:- XML 文件格式外观 . . 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?就像我在 @Tanaike 之前关于 Convert-API 的回答中学到的将 pdf 文件转换为 PNG 的 API 密钥链接一样? 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.您没有在任何地方分配 blob 的内容类型。 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.在方法 1 中,当您应该在从 Blob 创建的文件上设置名称时,您尝试在 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 .有关参考,请参阅类File

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Google Apps 脚本将文件从 URL 上传到 Google 云端硬盘 - Upload a file from URL to Google Drive with Google Apps Script 如何使用谷歌应用程序脚本使用 url 将音频文件上传到谷歌驱动器 - how to upload audio file to google drive with url with google apps script 使用谷歌应用脚本将文件从谷歌驱动器上传到外部 api - Upload files from google drive to external api using google apps script 使用 Google Apps 脚本将文件上传到 Google Drive - Upload File To Google Drive Using Google Apps Script 您如何创建 Google Drive 中的图像文件,然后将其插入到 Google Apps Script UrlFetchApp.fetch 对外部 API 的调用中? - How do you create and then insert an image file from Google Drive into a Google Apps Script UrlFetchApp.fetch call to an External API? Google Apps脚本-在= IMAGE()电子表格公式中使用云端硬盘中文件的网址 - Google Apps Script - Using URL of File in Drive in =IMAGE() Spreadsheet Formula 使用 Google Apps 脚本将文件上传到我的 google 驱动器(在 GOOGLE 中没有表格) - Upload file to my google drive with Google Apps Script (NO FORM IN GOOGLE) 使用 Google Apps 脚本从 Google Drive 中的多个上传元素上传本地文件 - Upload Local Files from multiple upload element in Google Drive using Google Apps Script 使用应用脚本将文件从Google云端硬盘加载到表单中 - Load File from Google Drive into a form using apps script 使用Google Apps脚本将文本文件上传到Google云端硬盘 - Upload text file to Google Drive with Google Apps Script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM