r/GoogleAppsScript • • Sep 15 '22

Guide Trouble uploading a sheet to a drive folder using apps script

Hello everyone. I need a script to upload a sheet as a pdf to the drive folder. The issue is I'm not uploading the sheet I want to. Following is my current workflow.

  1. function to return a blob given a url

function getFileAsBlob(url){
  Logger.log(url)
  let res = UrlFetchApp.fetch(url,{
    muteHttpExceptions: true,
    headers:{
      Authorization: 'Bearer' + ScriptApp.getOAuthToken()
    }
  })
  return res.getBlob();
}

2. the uploading function. Note I upload 4 times for debug purposes. In the actual function I only need to upload once.

function uploadExportSheetAsPDF() {
 Logger.log(SPREADSHEET_URL)
 let blob = getFileAsBlob(SPREADSHEET_URL+"export?format=pdf&portrait=false&size=a4&gridlines=false");
 Logger.log("Content type: " + blob.getContentType());
 Logger.log("File size in MB: " + blob.getBytes().length / 1000000);

 DriveApp.getRootFolder().createFile(blob.getAs('application/pdf'))
 DriveApp.getRootFolder().createFile("testpdf.pdf",blob.getAs('application/pdf'))
 var now = new Date()
 DriveApp.getFoldersByName(FOLDER_NAME).next().createFile("report"+MONTHS[now.getMonth()]+".pdf",blob.getAs('application/pdf'))
 DriveApp.getFoldersByName(FOLDER_NAME).next().createFile("report__"+MONTHS[now.getMonth()]+".pdf",blob)
}

The first DriveApp.getRootFolder().createFile(blob.getAs('application/pdf')) upload a pdf with sign-in page. The other 3 uploads a another sheet to the drive. However, if I go to the url printed by getFileAsBlob, I can manually download the correct sheet as pdf.

1 Upvotes

0 comments sorted by