1

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

Digital Farmer
  • 1,705
  • 5
  • 17
  • 67
  • 1
    Frederico, you could create the file directly in the folder after the `hasFile` check by utilizing the [`createFile()`](https://developers.google.com/apps-script/reference/drive/folder#createFile(String,String,String)) method on the folder itself (you will have to convert `Blob` to a string, though, as the method accepts content string) Btw, small note I forgot the last time - don't redefine variables such as `folder`: move its declaration to the function level, set it conditionally, then make the `hasFile` check and after that - create the file – Oleg Valter is with Ukraine Sep 28 '19 at 20:58
  • 1
    Another note is that if you are using the advanced service, you don't need to call the public API, after accessing `duplicate` file, you can call it via `{service name that you set}.Files.remove(duplicate.getId())` – Oleg Valter is with Ukraine Sep 28 '19 at 21:02
  • 1
    Although I'm not sure whether this is the direction you want, if you want to replace the PDF file without changing the file ID, you can also use the method of [Files: update](https://developers.google.com/drive/api/v3/reference/files/update). – Tanaike Sep 28 '19 at 23:35
  • I will be very honest with you, I tried to adjust in several ways but my weakness in programming ended up totally destroying the possibility of success ... I tried to edit the script in various ways but in all the result was still flawed. @Tanaike I'd like to have the script parse if there is a file in my Google Drive's SQUADS folder with the name I want to save the new file, if it exists, so that it deletes the old one and saves the new one. As if overwriting the old file. If it does not exist, it simply saves. – Digital Farmer Sep 29 '19 at 00:09
  • 2
    Thank you for replying. I could understand that you want to change the file ID for replacing the file. In this case, it is required to completely delete the existing file and create new file. By the way, I thought that an error might occur at this script of `var dres = UrlFetchApp.fetch(durl,'delete',{muteHttpExceptions: true, headers: {'Authorization': 'Bearer '+token}});`. How about this? – Tanaike Sep 29 '19 at 02:36
  • 2
    @Frederico Mattos, @Tanaike - my bad, yes (as fetch part was in my answer to part 1), its should be: `UrlFetchApp.fetch(durl,{method:'delete',headers:{'Authorization': 'Bearer '+token},muteHttpExceptions:true}); – Oleg Valter is with Ukraine Sep 29 '19 at 14:14

1 Answers1

2

Problem

Removing duplicate file and creating a new one in a target folder.

Solution

To expand on part 1 and comments, you could use the createFile() method on the target folder to ensure the new file is created directly in it and not in the Drive's root. The resulting modification of your script should look like this:

This sample assumes you named the advanced service DriveAPI when activating it. Also note that the folder declaration is moved to function scope to behave properly (don't declare variables in a smaller scope [in your case in an if...else statement] if you are going to use them in a wider one):

//...get token and Blob (do not create the file);

var fileName = spreadsheet.getSheetByName("Gerais").getRange("H2").getValue();

//Access or create the 'Squads' folder;
var folder; //declare folder;
var folders = DriveApp.getFoldersByName("Squads"); //returns iterator;
if(folders.hasNext()) {
  folder = folders.next();
}else {
  folder = DriveApp.createFolder("Squads");
}

//Remove duplicate file with the same name;
var existing = folder.getFilesByName(fileName); //returns iterator;
if(existing.hasNext()) {
  var duplicate = existing.next();

  //use either Drive API or Advanced service solution here;
}

//add file;
folder.createFile(pdfBlob).setName(fileName);

Advanced Drive service solution

DriveAPI.Files.remove(duplicate.getId());

Drive API solution

var durl = 'https://www.googleapis.com/drive/v3/files/'+duplicate.getId();
var dres = UrlFetchApp.fetch(durl,{
  method: 'delete',
  muteHttpExceptions: true,
  headers: {'Authorization': 'Bearer '+token}
});
if(dres.getResponseCode()>=400) {
  //handle errors;
}

Reference

  1. createFile() from Blob reference [Folder class];
  2. Drive advanced service reference;
  3. Files resource reference [Drive public API];
  4. Part 1 (see parameters handling);