Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

javascript - Google Apps Script: trying to read a text file from Google Drive with .getAs(MimeType.PLAIN_TEXT)

I'm stuck into trouble trying to read an HTML file from a Google Drive. So

I tried :

  1. to get a text with a help of UrlFetchApp.fetch("https://googledrive.com/host/{folderID}/{filename}.html"), but it fetches some google css file instead of mine.

  2. to convert a file from blob to a text string with file.getAs(MimeType.PLAIN_TEXT), and it just outputs "Blob" without any file content. How can I extract a file text without any specific libraries?

  var dApp = DriveApp;
  var folderIter = dApp.getFoldersByName("Лаборатории ФББ");
  var folder = folderIter.next();
  var filesIter = dApp.getFilesByName("Labs.html");

  var filelist = [];
  var propfiledate = 0;
  var propfilename;

  while(filesIter.hasNext()){

    var file = filesIter.next();
    var filename = file.getName();
    var fileurl = file.getUrl();
    var filedate = file.getDateCreated();

    if(filedate >= propfiledate){

      var propfiledate = filedate;
      var propfileurl = fileurl;
      var propfilename = filename;
      var propfile = file;

    }
  }

  Logger.log(propfile);

  // 1st try var myHtmlFile = UrlFetchApp.fetch(propfileurl);
  // 2nd try var myHtmlFile = propfile.getAs(MimeType.PLAIN_TEXT);
  // 3rd try var myHtmlFile = propfile.getBlob().text();
  
  var ss = SpreadsheetApp.create("test");
  SpreadsheetApp.setActiveSpreadsheet(ss);
  var sheet = ss.getActiveSheet();

  sheet.appendRow(myHtmlFile.toString().split("
"));

  Logger.log(propfiledate);
  Logger.log(propfilename);
  Logger.log(propfileurl);
}

question from:https://stackoverflow.com/questions/65885342/google-apps-script-trying-to-read-a-text-file-from-google-drive-with-getasmim

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using Apps Script on a dummy HTML file, you can get the HTML data that is inside of it.

Using DriveApp getFilesByName(name) method you retrieve the file by the name.

This will return a FileIterator since there can be many files with similar names.

Then you can get the file blob with getBlob() and the blob data as a string with getDataAsString()

I have managed to get the dummyHTML.html file data by using this previously mentioned methods:

function myFunction() {
  var files = DriveApp.getFilesByName("dummyHTML.html");
  while (files.hasNext()) {
    var file = files.next();
    Logger.log(file.getBlob().getDataAsString());
  }
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...