Home > Software design >  Get the blob of a drive file using Drive api
Get the blob of a drive file using Drive api

Time:03-10

I used below script to get the blob of abc.dat file which is generated via my Apps Script project. With the Drive service, it is easy. Used oauthScope is https://www.googleapis.com/auth/drive.readonly

function ReadData() {
  var files;

  var folders = DriveApp.getFoldersByName("Holder");
  if (folders.hasNext()) {
    var folder = folders.next();
    var files = folder.getFiles();

    while (files.hasNext()){
      file = files.next();
        if(file.getName()=='abc.dat'){
          var content = file.getBlob().getDataAsString();
          return content;
        }    
    }
  }
  return '';
}

In order to reduce the authentication scope, Now I am modifying the code to fully remove the https://www.googleapis.com/auth/drive.readonly oauthScope and use only the https://www.googleapis.com/auth/drive.file oauthScope.

Using the Drive api, I didn't found a direct way to get the blob of a file. I used this below script to get the blob of a word document file. But it is not working for the .dat file with error fileNotExportable, Export only supports Docs Editors files, code 403

function getBlob(fileID, format){

  var url = "https://www.googleapis.com/drive/v3/files/"   fileID   "/export?mimeType="  format;

  var blob = UrlFetchApp.fetch(url, {
    method: "get",
    headers: {"Authorization": "Bearer "   ScriptApp.getOAuthToken()},
    muteHttpExceptions: true
  }).getBlob();

  return blob;
}

Found this article and tried changing the export with get in the url. The returning blob.getDataAsString() gives "Not found" now.

The mimeType I used when creating the abc.dat file is application/octet-stream .dat. But when check the generated file, its mimeType is text/plain. So I used the 'text/plain' as the input for 'format' parameter in getBlob function.

.dat file creation code :

 var connectionsFile = {
      title: filename,
      mimetype: "application/octet-stream .dat",
      parents: [{'id':folder.getId()}],
    };
      var blobData = Utilities.newBlob(contents);
      file = Drive.Files.insert(connectionsFile,blobData);
  }

How can I modify this code to get the blob from the file? or is there any other way around?

Thanks in advance!

CodePudding user response:

I think that in your situation, it is required to use get method instead of export method. Because export method is used for Google Docs files (Document, Spreadsheet, Slides and so on). When your script is modified, how about the following modification?

Modified script:

function getBlob(fileID) {
  var url = "https://www.googleapis.com/drive/v3/files/"   fileID   "?alt=media";
  var blob = UrlFetchApp.fetch(url, {
    method: "get",
    headers: { "Authorization": "Bearer "   ScriptApp.getOAuthToken() },
    muteHttpExceptions: true
  }).getBlob();
  return blob;
}

Reference:

  • Related