Download file to google drive folder using app script - google-apps-script

I am using this script to download a URL set in a google sheet cell to a specific folder in google drive called "game_thumb"
If cell B1 is "yyyyy.com/picture.png" I expect picture.png to be downloaded to the google drive folder.
I get an error"ReferenceError: "DocsList" not defined. (line 5).
I also would like the file to be renamed to include Cell A1
(contentCellA1_picture.png) before it is downloaded to drive.
The code I use:
function getFile(fileURL) {
// see https://developers.google.com/apps-script/class_urlfetchapp
var response = UrlFetchApp.fetch(fileURL);
var fileBlob = response.getBlob()
var folder = DocsList.getFolder('game_thumb');
var result = folder.createFile(fileBlob);
debugger; // Stop to observe if in debugger
}

You want to save the downloaded file in the specific folder which has the name of game_thumb.
You want to set the value of cell "A1" to the filename of downloaded file.
If my understanding is correct, how about this modification?
For your question 1:
From your question, it is found that although I'm not sure whether the data is the file blob you want, the data from the URL can be retrieved. So in order to remove the error, please modify as follows.
From:
var folder = DocsList.getFolder('game_thumb');
To:
var folder = DriveApp.getFoldersByName('game_thumb').next();
In this modification, it supposes that the folder which has the name of game_thumb is only one in your Drive. If there are the folders with several same names, please tell me.
For your question 2:
Please modify as follows.
From:
var result = folder.createFile(fileBlob);
To:
var name = SpreadsheetApp.getActiveSheet().getRange("A1").getValue();
var result = folder.createFile(fileBlob).setName(name);
From your question, I'm not sure whether you are using the container-bound script or standalone script, and also I'm not sure where sheet there is the cell "A1" is. So this modification supposes that the cell "A1" of the active sheet is used.
References:
getFoldersByName()
getValue()
If I misunderstood your question and this modification didn't work, I apologize. At that time, can you provide the information of the situation?

Related

Update Google Doc Files With Data Pulled From a SpreadSheet Using Doc File Name

I need to assign a membership number to each request I receive from aspiring members of my association.
Aspiring members fill a Google Docs file. When their requests are validated, those files need to be updated with the assigned membership number.
Inside the spreadsheet I have two columns. One contains the membership number and the other contains the ID of the request.
Spreadsheet Screenshot
The doc files are named with the ID of the request as well. The membership numbers should be added in place of the placeholder {membershipnumber} found in the doc files.
Doc File Screenshot
Is anyone able to help?
Thanks a lot for your precious help!
I really have no idea how to accomplish this.
I believe your goal is as follows.
You have Google Document files in the specific folder and have a Google Spreadsheet including the values for updating the Google Document files.
You want to replace the value of {membershipnumber} with the values of column "A" by searching the filename using the value of column "C".
In this case, how about the following sample script?
Sample script:
In this sample, please copy and paste the following script to the script editor of Google Spreadsheet and set the variables. And, save the script.
function myFunction() {
const folderId = "###"; // Please set your folder ID of the folder including the Google Document files.
const sheetName = "Sheet1"; // Please set your sheet name.
const folder = DriveApp.getFolderById(folderId);
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const obj = sheet.getRange("A2:C" + sheet.getLastRow()).getDisplayValues().reduce((o, [a, , c]) => (o[c] = a.trim(), o), {});
const docs = folder.getFilesByType(MimeType.GOOGLE_DOCS);
while (docs.hasNext()) {
const file = docs.next();
const filename = file.getName().trim();
if (obj[filename]) {
const doc = DocumentApp.openById(file.getId());
doc.getBody().replaceText("{membershipnumber}", obj[filename]);
}
}
}
When this script is run, the Google Document files are updated using the values of column "A" by searching the Document files with the filename retrieved from column "C".
References:
reduce()
getFilesByType(mimeType)
replaceText(searchPattern, replacement)

google apps script. copy files to one drive

I would have files stored in google drive and I would like to copy (or move) those files to my OneDrive. I have managed to connect OneDrive to google drive and I can successfully create folders and upload files by file ID. I am trying to copy (or move) multiple files at once from google drive to OneDrive though without any luck yet. I am not good at programming just doing everything by tutorials only but yet could not find any working one. Maybe anyone could guide me how to do it? For the final idea I would like to achieve that files from google drive would be copied even to separate folders by the part of file title (name and surname, if to be exact). Currently I have "developed" such script:
function moveFiles(source, dest_folder) {
var source = DriveApp.getFolderById("1faFbaXJNziwIGyer2H2IPALQ8ahBfGMc");
var prop = PropertiesService.getScriptProperties();
var odapp = OnedriveApp.init(prop);
var files = DriveApp.getFiles();
while (files.hasNext()) {
var file = files.next();
var dest_folder =
OnedriveApp.init(PropertiesService.getScriptProperties()).uploadFile(files,
"/samplefolder");
}
}
I believe your current situation and your goal are as follows.
You are using OnedriveApp.
You have already been finished the authorization process. So you have already been had the access token and refresh token in the PropertiesServices.
You want to upload the files in a specific folder of Google Drive to a specific folder in OneDrive.
The number of files is 10 - 20.
The file size is small.
From your following reply
I have changed accordingly to: var files = file.getId(); but then I receive such error: TypeError: Cannot read property 'getId' of undefined moveFiles # srcpt.gs:5 If I use DriveApp.getFiles() or source.getFiles(), I receive such error: Exception: Unexpected error while getting the method or property getFileById on object DriveApp. convToMicrosoft # code.gs:629 OnedriveApp.uploadFile # code.gs:460 Appreciated for any help.
About var files = file.getId(); and If I use DriveApp.getFiles() or source.getFiles(), I receive such error:, unfortunately, I cannot understand it.
In this case, how about the following modification?
Modified script:
function myFunction() {
var prop = PropertiesService.getScriptProperties();
var odapp = OnedriveApp.init(prop);
var source = DriveApp.getFolderById("###"); // Please put your folder ID.
var files = source.getFiles();
while (files.hasNext()) {
var file = files.next();
odapp.uploadFile(file.getId(), "/samplefolder/"); // Please set the destination folder name. In this case, the folder name in OneDrive.
}
}
When "/samplefolder" is used, an error occurs. Please enclose the folder name by / like "/samplefolder/". Please be careful about this.
When this script is run, the files in the specific folder of Google Drive are copied to the destination folder of /samplefolder/ in OneDrive.
References:
OnedriveApp
getFolderById(id)
getFiles()

Script to save full Google Spreadsheet to folder

I want to create a function to save a spreadsheet to a folder.
I'm almost there, I think I just need to adjust the synthax of the createFile class.
Here is my code:
const spreadsheet2 = SpreadsheetApp.getActiveSpreadsheet();
var folder2 = DriveApp.getFoldersById("my_folder_id").next();
var filename2 = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("B97").getValue();
folder2.createFile([I think here is my missing command].setName(filename2));
Could someone finish it?
You want to copy the active Spreadsheet to the specific folder.
You want to use the filename from getActiveSheet().getRange("B97").getValue().
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
At DriveApp.getFoldersById("my_folder_id").next(), there is no method of getFoldersById. When you want to use the folder ID, please use DriveApp.getFolderById(folderId).
Unfortunately, the Spreadsheet cannot be directly created with createFile(). In your case, in order to copy the active Spreadsheet, you can use makeCopy().
When above points are reflected to your script, it becomes as follows.
Modified script:
var folderId = "###"; // Please set the folder ID you want to put the copied Spreadsheet.
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var filename2 = spreadsheet.getActiveSheet().getRange("B97").getValue();
var folder = DriveApp.getFolderById(folderId);
DriveApp.getFileById(spreadsheet.getId()).makeCopy(filename2, folder);
References:
getFolderById()
makeCopy()

Batch convert jpg to Google Docs

I have a folder of jpgs in Google Drive that I would like to convert to Google Docs. Now I can select each one manually and in the context menu "Open in Google Docs" This creates a new document with the image at the top of the page and OCR text below. I just want to do this with all my images.
There is a script here which converts gdoc to docx which I ought to be able to adapt for my case but I don't seem to be able to get it to work.
Here is my adapted script:
function convertJPGtoGoogleDocs() {
var srcfolderId = "~~~~~~~~~Sv4qZuPdJgvEq1A~~~~~~~~~"; // <--- Please input folder ID.
var dstfolderId = srcfolderId; // <--- If you want to change the destination folder, please modify this.
var files = DriveApp.getFolderById(srcfolderId).getFilesByType(MimeType.JPG);
while (files.hasNext()) {
var file = files.next();
DriveApp.getFolderById(dstfolderId).createFile(
UrlFetchApp.fetch(
"https://docs.google.com/document/d/" + file.getId() + "/export?format=gdoc",
{
"headers" : {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()},
"muteHttpExceptions" : true
}
).getBlob().setName(file.getName() + ".docx")
);
}
}
Can anyone help?
Thanks.
You want to convert Jpeg files in a folder as Google Document.
When the Jpeg file is converted to Google Document, you want to use OCR.
If my understanding is correct, how about this modification?
Modification points:
In the script you modified, MimeType.JPG returns undefined. So the script in while is not run.
Please use MimeType.JPEG.
The script of this answer is used for exporting Google Document as Microsoft Word. Unfortunately, that script cannot be directly used for converting Jpeg file to Google Document.
If you want to modify the script of this answer, how about modifying as follows?
When you use this script, please enable Drive API at Advanced Google Services. By this, the API is automatically enabled at API console. The specification of Google Apps Script Project was Changed at April 8, 2019.
Modified script:
function convertJPGtoGoogleDocs() {
var srcfolderId = "~~~~~~~~~Sv4qZuPdJgvEq1A~~~~~~~~~"; // <--- Please input folder ID.
var dstfolderId = srcfolderId; // <--- If you want to change the destination folder, please modify this.
var files = DriveApp.getFolderById(srcfolderId).getFilesByType(MimeType.JPEG); // Modified
while (files.hasNext()) {
var file = files.next();
Drive.Files.insert({title: file.getName(), parents: [{id: dstfolderId}]}, file.getBlob(), {ocr: true}); // Modified
}
}
Note:
If there are a lot of files in the source folder, there is a possibility that the limitation of script runtime (6 min / execution) exceeds.
References:
Enum MimeType
Drive.Files.insert
If I misunderstand your question, please tell me. I would like to modify it.

Insert Image into Spreadsheet Cell from Drive using Google Apps Script

I would like to be able to add an image file into my spreadsheet from Google Drive. I see there is a built-in image function available =image, but this requires a URL and that image files should be shared publicly on the internet. However, I am working with digital assets and can not share them publicly.
I have the following code, this works but does not add to the required cell. Is this at all possible?
function insertImageFromDrive(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var fileId = '0B5UAkV0avfiKNGYtd1VzUzlsTVk';
var img = DriveApp.getFileById(fileId).getBlob();
sheet.insertImage(img, 4, 3)
}
Try using the guide Insert image in a spreadsheet from App Script:
function insertImageOnSpreadsheet() {
var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
// Name of the specific sheet in the spreadsheet.
var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
var response = UrlFetchApp.fetch(
'https://developers.google.com/adwords/scripts/images/reports.png');
var binaryData = response.getContent();
// Insert the image in cell A1.
var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
sheet.insertImage(blob, 1, 1);
}
Just replace the necessary values. The part where you indicate which cell you insert the image is in:
sheet.insertImage(blob, 1, 1);
There is a google spreadsheet add-on ImageKit to help insert multiple images from difference sources including Google Drive, check it out > https://chrome.google.com/webstore/detail/imagekit/cnhkaohfhpcdeomadgjonnahkkfoojoc
Here you find a screenshot of tool's interface.
It is not possible if the drive image file is not public on your google drive, Having said that there is a trick to overcome i.
First make sure the image file is temporary public on your drive. you can do that also via app script by changing the file permissions to DriveApp.Access.ANYONE, DriveApp.Permission.EDIT. Then the drive file is like a file as if it was from the internet. You can then add the blob.
After that you can decide two things.
Change the permissions back or remove the image file from your drive (if you only want to use it embedded in your blob (also via app script code if you want)
good luck
I don't think it is currently possible, see here: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3303
Here's another alternative:
var fileId = "..."; // your image's google drive id
sheet.insertImage("https://docs.google.com/uc?id=" + fileId, column, row);
Just make sure your file has link sharing turned on (anyone with the link can view) otherwise this method won't work.
Documentation