1
votes

I need a script to use with google sheets to save a list of .img urls to specific google drive folder with file naming from another cell.

For Example:
Column A - File URL
/imagefilepath.jpg
Column B - Save as name
image_1

Auto save /imagefilepath.jpg to google drive folder "Test" with "image_1" file name.

Is that possible?

New to scripts.. need some advice/pointers or working script (even better)!

Currently got the following:

    /**
 * Uploads a new file to the user's Drive.
 */
function uploadFile() {
  var imgurl = 'https://www.w3schools.com/w3css/img_lights.jpg';
  var image = UrlFetchApp.fetch(imgurl).getBlob();
  var filename = setName('test');
  var folder = DriveApp.getFoldersByName(folder);
    if (folder != null) {
      var file = DriveApp.createFile(image);
    }

  Logger.log('ID: %s, File size (bytes): %s', file.id, file.fileSize);
}

But it saves as url name into the root of google drive and only if I insert the img urls into the script. How do i make it dynamic?

P.s found a few scripts on here but all seem to be outdated/dont work. I have over 2000 urls and different file names.

2

2 Answers

2
votes

Try this:

function uploadFile() {
  var imgurl = 'https://www.w3schools.com/w3css/img_lights.jpg';
  var image = UrlFetchApp.fetch(imgurl).getBlob().getAs('image/jpeg').setName('test');
  var folder = DriveApp.getFolderById('FolderId');
  var file = DriveApp.createFile(image);
  Drive.Files.update({"parents": [{"id": folder.getId()}]}, file.getId());
}

So your final function should look something like this:

function uploadFiles() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var rg=sh.getDataRange();
  var vA=rg.getValues();
  for(var i=0;i<vA.length;i++) {
    var imgurl=vA[i][0];//Column A for url
    var name=vA[i][1];//Column B for filename
    var image=UrlFetchApp.fetch(imgurl).getBlob().getAs('image/jpeg').setName(name);
    var folder=DriveApp.getFolderById('1aIawMeJCjB1GWaV6URH3jkV4xUJhaYLV');
    var file=DriveApp.createFile(image);
    Drive.Files.update({"parents": [{"id": folder.getId()}]}, file.getId());
  }
}
0
votes

I made a modification to MetaMan's great answer so that the QRs (in column A1:A) for URLs to a Google Form with pre-fill responses could be uploaded to the Drive (with the new names for the files in column B1:B).

    function uploadFiles() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('MY SHEET NAME');
var rg=sh.getDataRange();
var vA=rg.getValues();
for(var i=0;i<vA.length;i++) {
var imgurl="https://api.qrserver.com/v1/create-qr-code/?size=300x300&data="+encodeURIComponent(vA[i][0]);//Column A for url
var name=vA[i][1];//Column B for filename
var image=UrlFetchApp.fetch(imgurl).getBlob().getAs('image/jpeg').setName(name);
var folder=DriveApp.getFolderById('MY FOLDER ID');
var file=DriveApp.createFile(image);
Drive.Files.update({"parents": [{"id": folder.getId()}]}, file.getId());
}
}