Need sheets script to save img to drive - google-apps-script

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.

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

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

Related

Check a specific file in Google drive folder with Google Script

I'm looking for a script to achieve the following. Tried googling few codes but they don't seem to address what I require. And since I'm new to scripts, I'm kind of lost on this.
Check name listed in "Column H" in google sheet and find matching file in Google Drive (need to give a path).
If matches, display the hyperlink to the file in "Column I"
And also the script should check through all the rows in the sheet, and do the above for each row.
And stop checking if Column "Column K" has as "Complete"
Thank you in advance.
The code I was trying the modify for this is follows;
var searchFor ='title contains "2013"';
var names =[];
var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
names.push(file.getName());
}
var folders = DriveApp.searchFolders(searchFor);
while (folders.hasNext()) {
var file = folders.next();
names.push(file.getName());
}
for (var i=0;i<names.length;i++){
Logger.log(names[i]);
}
}```
Here is my solution. Feel free to change the size range of column H ('H2:Hx') :
function myFunction() {
var folderId = '#FolderId';
var folder = DriveApp.getFolderById(folderId)
var extension = '.xlsx';
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheetByName('Sheet1');
var RowSize=sheet.getRange('H:H').getValues().filter(String).length; //calculate max value of rows
var file_name=sheet.getRange('H2:H'+RowSize).getValues()
var file_checker=sheet.getRange('K2:K'+RowSize).getValues()
for (i = 0; i < file_name.length; i++) {
if (file_checker[i][0]=="Complete"){break;}
var files = folder.getFilesByName(file_name[i][0]+extension)
while (files.hasNext()) {
var childFile = files.next();
var file_url = childFile.getUrl()
sheet.getRange(i+2,9).setValue(file_url);
} // while
} //for
} // function

Google Script get files names into spreadsheet issues

I made a code App Script that lists all the Folder Names and Files names into a Spreadsheet which works good until I rename one of the folders or file. Then the next time I run the script it will not include the renamed Folder/File into the Spreadsheet. Is there something I have done wrong in the script?
Thanks in advance for the help.
Link to spreadsheet: https://docs.google.com/spreadsheets/d/1T3eKmyXKhLCbcoMdZRzMQ1__-dL3bTlH0wMKaWVFJ1Y/edit?usp=sharing
Link to Google Script: https://script.google.com/d/1LVTe29Y3jDbElt8LM4ciZ8Kj0gPzmFAxawZaYmRaFvkkfrewtJ5fxO0B/edit?usp=sharing
Link to Folder: https://drive.google.com/drive/folders/1VPQC9Cp4QT0r_ILmq9c0nOsSSduqh6jg?usp=sharing
function listFolders(folder) {
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1T3eKmyXKhLCbcoMdZRzMQ1__-dL3bTlH0wMKaWVFJ1Y/edit#gid=0');
var first = ss.getSheetByName("Sheet1");
first.clear("A2:D405");
var sheet = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1T3eKmyXKhLCbcoMdZRzMQ1__-dL3bTlH0wMKaWVFJ1Y/edit#gid=0');
sheet.appendRow(["File Name", "URL", "Folder Name"]);
var folder = DriveApp.getFolderById('1VPQC9Cp4QT0r_ILmq9c0nOsSSduqh6jg');
var subfolders = folder.getFolders();
while (subfolders.hasNext()) {
//Logger.log(folder);
var name = subfolders.next();
while (subfolders.hasNext()) {
//Logger.log(folder);
var name = subfolders.next();
var files = name.getFilesByType('application/vnd.google-apps.spreadsheet');
var cnt = 0;
var file;
while (files.hasNext()) {
var file = files.next();
cnt++;
Logger.log(file);
Logger.log(cnt);
data = [
file.getName(),
file.getUrl(),
name, //folder name
];
sheet.appendRow(data);
};
}
}
}

How to write google script to automatically call data from a google folder drive that contains a CSV file into one Google Sheets

I am trying to write a google script that will allow me to go into my google drive folder called "MeadJohsnon" and pull 'Temperature Calibration.csv' to google sheets. I have never used google script before. Currently I have the "Save Email and Attachment" Add-ons. This add-on is pulling .cvs files that my team is sending me from the field. They use "TapForms" and then send the form via email to my gmail. So, I got the email sending that attachment to my google drive but I need help with the script, so Drive will automatically get those .cvs files and put the information into one google sheet. I say ONE google sheet because although I have a team sending in forms, all the forms have the same information on them.
This is what I have done so far. The fourth line gives me a
function loadingCSV() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sht=ss.getActiveSheet();
sht.clearContents();
var data = loadFile();
var dataA =Utilities.parseCsv(data);
var rng = sht.getRange(1, 1, dataA.length, dataA[0].length);
rng.setValues(dataA);
}
I would just like feedback on how to fix my error or what I could do instead. As stated this is my first time using google script, my specialty is ASP.net lol not script. Thank you.
function loadingCSV() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sht=ss.getActiveSheet();
sht.clearContents();
var data = loadFile();
var dataA =Utilities.parseCsv(data);
var rng = sht.getRange(1, 1, dataA.length, dataA[0].length);
rng.setValues(dataA);
}
function loadFile(filename,folderID)
{
var filename = (typeof(filename) !== 'undefined')? filename : 'Temperature Calibration.csv';
var folderID = (typeof(folderID) !== 'undefined')? folderID : '0B8m9xkDP_TJxUUlueHhXOWJMbjg';
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var s = '';
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
s = fi.getBlob().getDataAsString();
}
}
return s;
}
Okay this will append the files to the active spreadsheet you'll probably have to open the spreadsheet by id and use getSheetByName to get the sheet you want because this spreadsheet probably won't be active all the time when the trigger is running. I assume the the files all end in .csv. I rename them to .old after reading the data so that the program won't read them multiple times.
function appendingCSV() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sht=ss.getActiveSheet();
var drng = sht.getDataRange();
var lastRow = drng.getLastRow();
var data = loadFiles();
var dataA =Utilities.parseCsv(data);
if(dataA.length>0)
{
var rng = sht.getRange(lastRow + 1, 1, dataA.length, dataA[0].length);
rng.setValues(dataA);
}
else
{
SpreadsheetApp.getUi().alert('No Data Returned from LoadFiles');
}
}
function loadFiles(folderID)
{
var folderID = (typeof(folderID) !== 'undefined')? folderID : '0B8m9xkDP_TJxUUlueHhXOWJMbjg';
var fldr = DriveApp.getFolderById(folderID);
var files = fldr.getFiles();
var s='';
var re = /^.*\.csv$/i;
while (files.hasNext())
{
var file = files.next();
var filename = file.getName();
if(filename.match(re))
{
s += file.getBlob().getDataAsString() + '\n';
file.setName(filename.slice(0,-3) + 'old');
}
}
return s;
}

A script to copy one sheet to various spreadsheets in a specific folder in Google Drive

I have a sheet which I need to copy to hundreds of spreadsheets in a given folder in Google Drive. I am just beginning with script and I do not know how to proceed because the script below just gives me an error. Thanks.
function myFunction() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[0];
var folder = DriveApp.getFoldersByName('TEST FOR SCRIPT');
var contents = folder.getFiles();
for (var i = 0; i < contents.length; i++) {
file = contents[i];
}
sheet.copyTo(contents).setName('ANSWERS');
}
I was given this answer by someone within a community in Google+ and it works:
function copyToSheets() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[1];
var folders = DriveApp.getFoldersByName('ID');
var firstFolder = folders.next();
var folderFiles = firstFolder.getFiles();
var thisFile;
while (folderFiles.hasNext()) {
thisFile = folderFiles.next();
var currentSS = SpreadsheetApp.openById(thisFile.getId());
sheet.copyTo(currentSS);
currentSS.getSheets()[currentSS.getSheets().length-1].setName('NAME');
}
}
This line of code:
var folder = DriveApp.getFoldersByName('TEST FOR SCRIPT');
returns a FolderIterator. Even if you only have one folder by that name, the getFoldersByName() method returns an object, that you can't use the getFiles() method on directly. The getFiles() method works on the Files Class. It is not available to the Folder Iterator. After you get the Folder Iterator, you must use the next() method to get the first (and probably only) folder in the object.
function getAllFilesInFolder() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[0];
var folders = DriveApp.getFoldersByName('Folder Name Here');
var firstFolder = folders.next();
var folderFiles = firstFolder.getFiles();
var thisFile;
while (folderFiles.hasNext()) {
thisFile = folderFiles.next();
Logger.log(thisFile.getName());
};
};
And also use hasNext() to loop through the files. There doesn't seem to be an length property of the Files object.

How to select a specific folder from Google Drive and upload a file into it?

As i m trying to upload a file into a specific folder,but i can not find an object which can select a specified folder from Drive,
as i tried here...
function doGet(e){
var app=UiApp.createApplication();
var panel=app.createHorizontalPanel();
var month1=app.createListBox().addItem("January").addItem("Febuary").addItem("March").setId("month12").setName("month12");
var upload=app.createFileUpload().setName("file");
var uploadbutton=app.createSubmitButton("UPLOAD");
panel.add(month1).add(upload).add(uploadbutton);
var form=app.createFormPanel();
form.add(panel);
app.add(form);
return app;
}
function doPost(e){
var app=UiApp.createApplication();
var month=e.parameter.month12;
var file=e.parameter.file; //user upload fileName
var files = DriveApp.getFolders();
while (files.hasNext()) {
var file = files.next();
var fileName=file.getName();
if(month==fileName){
var doc = DocsList.createFile(file); //that directly uploaded into the Drive List
Logger.log("inside");
}
}
return app;
}
DocsList directlly upladed a file into the Drive,if i use DriveApp.CreateFolder then it is creating a folder into the drive.
Try using the (folder).createfile("file") instead of the DocList function. i.e.
var folder = DocsList.getFolder("MyFolder");
var fileBlob = Utilities.newBlob(e.parameter.file); // process blob ready to save
var doc = folder.createFile(fileBlob); // createfile in specified folder