How to convert bloburl/objecturl for Google Apps Script createFile() API?

Solution 1:

From your replying, I confirmed that your audioBlobUrl is like blob:https://n-gtuqz5opiogjdwjt5bm3j7sgiq5rl4g7osg6piq-0lu-script.googleusercontent.com/a9f62d15-c7c1-41c0-ac5d-0a05dcb01fa6. In this case, unfortunately, this URL cannot be directly used. So in order to use this at Google Apps Script, it is required to convert to the data. In this answer, I would like to propose the sample script for converting the URL to the data (in this case, the URL is converted to the byte array.). By this, the data can be decoded at Google Apps Script, and the data can be saved as a file.

Modified script:

Javascript side:

As a simple sample script, When your audioBlobUrl and filename are used, please use the following script.

fetch(audioBlobUrl).then(r => r.blob()).then(blob => {
  var fr = new FileReader;
  fr.onload = f => {
    var obj = {data: [...new Int8Array(f.target.result)], mimeType: blob.type, filename};
    google.script.run.withSuccessHandler(onSuccess).uploadFiles(obj);
  };
  fr.readAsArrayBuffer(blob);
});

Google Apps Script side:

At the Google Apps Script side, please modify uploadFiles as follows.

function uploadFiles({data, mimeType, filename}) {
  var file = Utilities.newBlob(data, mimeType, filename || "sampleFilename");
  var folder = DriveApp.getFolderById('1UWGb5Mzr9VzPUuQTr9CWD7EMYNEAzyuC');
  var createFile = folder.createFile(file);
  return createFile.getUrl();
}

Note:

  • google.script.run is run with the asynchronous process. It seems that google.script.run is used in a loop. Although I'm not sure about your whole script, if the asynchronous process will become your new issue, please modify it.

  • This modified script supposes that your audioBlobUrl is like blob:https://n-gtuqz5opiogjdwjt5bm3j7sgiq5rl4g7osg6piq-0lu-script.googleusercontent.com/a9f62d15-c7c1-41c0-ac5d-0a05dcb01fa6 from your replying. Please be careful this.

  • I'm not sure about your actual situation from your question. When you are using your script as the Web Apps, when you modified the script, please reflect the latest script to the Web Apps. Please be careful about this.

Reference:

  • fetch(url)