Home > Mobile >  Google Drive file when upload duplicating same name
Google Drive file when upload duplicating same name

Time:07-01

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"); 
}

CodePudding user response:

Delete old files with same name

function myFunction() {
  var url  ="https://html.com/wp-content/uploads/flamingo.jpg";
  var response = UrlFetchApp.fetch(url);
  var blob=response.getAs('image/jpeg');
  var folderid = "1WnbHBPcYd9S4XwXpcYEMX32k********";
  const folder = DriveApp.getFolderById(folderid);
  var fileName=decodeURIComponent(url.split("/").pop());
  var files = folder.getFilesByName(fileName);
  while(files.hasNext()) {
    let file = files.next();
    Drive.Files.remove(file.getId());
  }//deletes oldfiles with same name
  var file=folder.createFile(blob);
  file.setName("image.jpeg"); 
}

CodePudding user response:

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);
}
  • Related