Skip to content
Advertisement

Google Drive file when upload duplicating same name

When i run a program in google script for upload image from url to drive.program run successful. But i want overwrite the same file in same name not multiple files

This is my code :

function myFunction() {
  var url  ="https://html.com/wp-content/uploads/flamingo.jpg";
  var response = UrlFetchApp.fetch(url);
  console.log(response.getResponseCode());
  var blob=response.getAs('image/jpeg');
  var folder = "1WnbHBPcYd9S4XwXpcYEMX32k********";
  var fileName=decodeURIComponent(url.split("/").pop());
  
  console.log("File named : "+fileName);
  var file=DriveApp.getFolderById(folder).createFile(blob);
  // Set the name to the created file after creating it!
  file.setName("image.jpeg"); 
}

Advertisement

Answer

I Got Correct Solution This is work fine for me

function myFunction() {
  var response = UrlFetchApp.fetch("https://html.com/wp-content/uploads/flamingo.jpg");
  var blob=response.getAs('image/jpeg');
  var folderid = "1WnbHBPcYd9S4XwXpcYEM********";
  const folder = DriveApp.getFolderById(folderid);
  var files = folder.getFilesByName("flamingo.jpg"); // Duplicate File Name
  while(files.hasNext()) {
    let file = files.next();
    Drive.Files.remove(file.getId());
  }//deletes oldfiles with same name
  var file=folder.createFile(blob);
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement