When testing the script this way, when there is no file in the SQUADS
folder with the name I want to save, it actually saves in the SQUADS folder.
However, when there is a file with the name I want, it saves the new PDF in the main Google Drive folder, the correct would be to delete the existing one in the SQUADS
folder and save in the SQUADS
folder
Something is missing and I still don't understand how I can solve
var token = ScriptApp.getOAuthToken();
var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' + token } });
var pdfBlob = docurl.getBlob();
// Get filename from sheet "Work", cell "B5"
var fileName = spreadsheet.getSheetByName("Gerais").getRange("H2").getValue();
// Create file from blob and name it
// The newFile is placed in the root folder by default
var newFile = DriveApp.createFile(pdfBlob).setName(fileName);
// if folder exists use next
if (DriveApp.getFoldersByName("Squads").hasNext()){
var folder = DriveApp.getFoldersByName("Squads").next();
// if folder does not exist
} else {
var folder = DriveApp.createFolder("Squads");// new folder created in the root folder by default
}
//prepare new file and Squads folder;
var existing = folder.getFilesByName(fileName); //returns file iterator;
var hasFile = existing.hasNext(); //check if iterator isn't empty;
if(hasFile) {
var duplicate = existing.next(); //access file;
//delete file;
var durl = 'https://www.googleapis.com/drive/v3/files/'+duplicate.getId();
var dres = UrlFetchApp.fetch(durl,'delete',{
muteHttpExceptions: true,
headers: {'Authorization': 'Bearer '+token}
});
if(dres.getResponseCode()>=400) {
//handle errors;
}
}
//continue: add file, remove from root, etc;
folder.addFile(newFile); // add new file to folder
DriveApp.removeFile(newFile); // remove file from root folder
Already authorized as seems necessary in Resources → Google Advanced Services → Drive API V2