Uploading a file to Google Shared Drive via Spreadsheet - google-apps-script

I'm trying to use google spreadsheets to upload files to a certain folder on a Shared Drive. I've found this code online and it didn't actually work to start with but I played with it and it would still not initiate the upload.
The code I used came from this website.
I've modified the upload function:
folderId = 'my folder ID'
driveId = 'my shared drive ID'
function onOpen(e){
var ss = SpreadsheetApp.getActiveSpreadsheet()
var menuEntries = [];
menuEntries.push({name: "File", functionName: "doGet"});
ss.addMenu("Attach", menuEntries);
}
//the upload script
function upload(obj) {
var metadata = {
"parents": [{
"id": folderId,
"kind": "drive#parentReference"
}],
"teamDriveId": driveId };
var optionalParams = {
"supportsAllDrives": true
};
file = Drive.Files.insert(metadata, optionalParams);
var activeSheet = SpreadsheetApp.getActiveSheet();
var File_name = file.getName()
var value = 'hyperlink("' + file.getUrl() + '";"' + File_name + '")'
var activeSheet = SpreadsheetApp.getActiveSheet();
var selection = activeSheet.getSelection();
var cell = selection.getCurrentCell()
cell.setFormula(value)
return {
fileId: file.getId(),
mimeType: file.getMimeType(),
fileName: file.getName(),
};
}

I think the obj refers to the type of file you are uploading maybe, you can review the proper code in this documentation https://developers.google.com/drive/api/v3/manage-uploads#multipart
Just make sure to select "Java."
Here is the example in that KB:
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());

Related

I want to change the names of old files uploaded to Google Forms

I have a google form and all the files uploaded by the participants contain random names.
The data is summarized in personal photos, ID photos, photos of certificates.
That is why we want to name the files with the names of the people themselves by choosing a specific field.
I tried in a code via the google apps script to change the names but it is no more than 70 to 80 files and then it stops
Is there a code that will help me with this work, especially since the number of files is large?
function renamefile() {
var form = FormApp.openById('16aPNgaSuDZ-e0ibw08jW7_-YMULGWV-_iUP9uQHE'); //DDD
var formResponses = form.getResponses();
var baseString = 'https://drive.google.com/file/d/';
var endString = '/view?usp=drivesdk';
var folder = DriveApp.getFolderById('1BPA7wkECV1vOB6bo3tGfUZd9MifjwYJG2BVI_sHSeNojFY-xiN4dvLW_vc2zw4IEe');
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var itemResponses = formResponse.getItemResponses();
var itemResponseFname = itemResponses[1];
var itemResponsePhoto = itemResponses[15];
var photoID = itemResponsePhoto.getResponse();
var newName = itemResponseFname.getResponse() + " - " + "PHOTO" ;
var url = baseString + photoID + endString;
var urlCheck = file.getUrl();
if ( url == urlCheck) {
var modName = newName + ".pdf" ;
file.setName(modName);
}
}
}
}
Modification points:
From your showing script, it seems that the form responses are retrieved every loop of the "while loop". I thought that this might be a high process cost.
From your script, it seems that you want to rename PDF files. In this case, when PDF files are retrieved. The process cost might be able to be reduced.
I thought that in your situation, the file ID can be used for checking the file instead of URL.
When these points are reflected in your script, how about the following modification?
Modified script:
function renamefile() {
var form = FormApp.openById('###'); // Please set your file ID of Google Forms.
var folder = DriveApp.getFolderById('###'); // Please set your folder ID.
// Create an object for searching file ID.
var obj = form.getResponses().reduce((o, f) => {
var itemResponses = f.getItemResponses();
var itemResponseFname = itemResponses[1];
var itemResponsePhoto = itemResponses[15];
var fileId = itemResponsePhoto.getResponse();
var newName = itemResponseFname.getResponse() + " - " + "PHOTO";
o[fileId] = newName + ".pdf";
return o;
}, {});
// Rename files.
var files = folder.getFilesByType(MimeType.PDF);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();
if (obj[fileId]) {
file.setName(obj[fileId]);
}
}
}
When this script is run, first, an object is created. This object is used for searching the file ID in the folder. And, using the object, the PDF files in the folder are renamed.
Note:
If your files are not PDF files, please modify var files = folder.getFilesByType(MimeType.PDF); to var files = folder.folder.getFiles();.
When the number of files is large and the processing time is over 6 minutes, I would like to propose using the batch requests. The sample script of batch request can be seen at this thread. And, when the above script is modified, the sample script is as follows. When you use this script, please enable Drive API at Advanced Google services. And also, please install a Google Apps Script library of BatchRequest. Ref
function renamefile2() {
var form = FormApp.openById('###'); // Please set your file ID of Google Forms.
var folderId = "###"; // Please set your folder ID.
// Create an object for searching file ID.
var obj = form.getResponses().reduce((o, f) => {
var itemResponses = f.getItemResponses();
var itemResponseFname = itemResponses[1];
var itemResponsePhoto = itemResponses[15];
var fileId = itemResponsePhoto.getResponse();
var newName = itemResponseFname.getResponse() + " - " + "PHOTO";
o[fileId] = newName + ".pdf";
return o;
}, {});
// Rename files using batch request.
var { items } = Drive.Files.list({ q: `'${folderId}' in parents and trashed=false and mimeType='${MimeType.PDF}'`, maxResults: 1000, fields: "items(id)" });
var requests = items.reduce((ar, { id }) => {
if (obj[id]) {
ar.push({
method: "PATCH",
endpoint: `https://www.googleapis.com/drive/v3/files/${id}`,
requestBody: { name: obj[id] },
});
}
return ar;
}, []);
var result = BatchRequest.EDo({ batchPath: "batch/drive/v3", requests });
}
In this sample, it supposes that the number of your files is less than 1000. When the number of files is more than 1000, please retrieve all files using pageToken.
Reference:
reduce()

Get folders and files listed in Google Sheets from a google drive folder using a Google Apps script

I have a Google sheet where a user can cut and paste the google drive folder URL, and it will extract the folder ID. This is extracted in a named range "FolderID".
I then want to list the folders and files in the folder (subfolders and files within as well if possible) into the worksheet "Files".
I have played around with another script I wrote, but am coming up with an error for the initial folders list (I haven't gotten to the files list yet).
I get this error: Exception: Unexpected error while getting the method or property getFolderById on object DriveApp.
The current script is:
function listFoldersAndFilesInAFolder() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName('Files');
var foldername = ss.getRangeByName('FolderID');
sh.clearContents();
sh.appendRow(["Name", "Link"]);
var fA = [];
var folders = DriveApp.getFolderById(foldername).getFolders();//Enter folder id
while (folders.hasNext()) {
var folder = folders.next();
var folderURLstart = "https://drive.google.com/drive/folders/"
fA.push([folder.getName(), folderURLstart + folder.getId()]);
}
sh.getRange(sh.getLastRow() + 1, 1, fA.length, 2).setValues(fA);
sh.getRange(2, 1, sh.getLastRow() - 1, 2).sort({ column: 1, ascending: true });
}
Can anyone help:
fix the script above so I can list folders.
direct me on what to add to list files, and subfolders and files?
To add list of files, subfolders and files, use
function listFilesAndFolders() {
var folderid = '18akqHAN7PSPMnG3h5HpCskQsMCv4TqCM'; // change FolderID
var sh = SpreadsheetApp.getActiveSheet();
sh.clear();
sh.appendRow(["parent","folder", "name", "update", "size", "URL", "ID", "description", "type"]);
try {
var parentFolder =DriveApp.getFolderById(folderid);
listFiles(parentFolder,parentFolder.getName())
listSubFolders(parentFolder,parentFolder.getName());
} catch (e) {
Logger.log(e.toString());
}
}
function listSubFolders(parentFolder,parent) {
var childFolders = parentFolder.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
Logger.log("Fold : " + childFolder.getName());
listFiles(childFolder,parent)
listSubFolders(childFolder,parent + "|" + childFolder.getName());
}
}
function listFiles(fold,parent){
var sh = SpreadsheetApp.getActiveSheet();
var data = [];
var files = fold.getFiles();
while (files.hasNext()) {
var file = files.next();
data = [
parent,
fold.getName(),
file.getName(),
file.getLastUpdated(),
file.getSize(),
file.getUrl(),
file.getId(),
file.getDescription(),
file.getMimeType()
];
sh.appendRow(data);
}
}
https://docs.google.com/spreadsheets/d/13fHMrWR9OOWa045uJbkz67YoVkOG4Pg6ScvrRpE-WBc/copy

Apps script - export JSON-file from spreadsheet with replacement old file

I need a little help with my script, I wrote by help from internet.
I export data from spreadsheet to json-file and save it on google-drive, but every new file doesn't replace old file. Script creates new file with ending at name of new file (1), (2) etc:
exp_planning.json - this file I need
exp_planning(1).json - this file and other with I not need
Be happy for your help! Thank you, friends!))
function convertSheet2JsonText(sheet) {
// first line(title)
var colStartIndex = 1;
var rowNum = 1;
var firstRange = sheet.getRange(1, 1, 1, 15);
var firstRowValues = firstRange.getValues();
var titleColumns = firstRowValues[0];
// after the second line(data)
var lastRow = sheet.getRange("A2:A").getValues().filter(String).length;
var rowValues = [];
for(var rowIndex = 2; rowIndex <= lastRow; rowIndex ++ ) {
var strRange = sheet.getRange(2, 1, rowIndex, 1).getValue();
if(strRange != "") {
var colStartIndex = 1;
var rowNum = 1;
var range = sheet.getRange(rowIndex, colStartIndex, rowNum, 15);
var values = range.getValues();
rowValues.push(values[0]);
}
}
// create json
var jsonArray = [];
for(var i=0; i<rowValues.length; i++) {
var line = rowValues[i];
var json = new Object();
for(var j=0; j<titleColumns.length; j++) {
json[titleColumns[j]] = line[j];
}
jsonArray.push(json);
}
//return jsonArray;
Logger.log(jsonArray);
var blob,file,fileSets,obj;
var folder = DriveApp.getFoldersByName('JSON_EXPFILES').next();
fileSets = {
title: 'exp_planning.json',
mimeType: 'application/json',
"parents": [
{
"id": folder.getId(),
"kind": "drive#parentReference"
}
]
};
blob = Utilities.newBlob(JSON.stringify(jsonArray), "application/vnd.google-apps.script+json");
file = Drive.Files.insert(fileSets, blob);
Logger.log('ID: %s, File size (bytes): %s, type: %s', file.id, file.fileSize, file.mimeType);
}
function doGet() {
var sheetName = "для ТК";
var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
var json = convertSheet2JsonText(sheet);
return ContentService
.createTextOutput(JSON.stringify(json))
.setMimeType(ContentService.MimeType.JSON);
}
I found one way with deleting old file before creating new...
var allFiles = folder.getFilesByName(fileSets.title);
while (allFiles.hasNext()) {
file = allFiles.next();
file.getParents().next().removeFile(file);
}
but may be there is anything else about replacement old file?
I believe your goal as follows.
When you create a new file of exp_planning.json in the specific folder, you want to remove the existing files, which are the same filename, in the specific folder. And then, you want to create new file to the folder.
Modification points:
In your script, the file of exp_planning.json is created to the specific folder using Drive.Files.insert(). In this case, the files with the same filename are created. So, it is required to check the existing files and create the new file. But, when I saw the script of I found one way with deleting old file before creating new..., removeFile of Class Folder is used. This had been used for removing the given file from the current folder. In the current stage, this method was deprecated. Ref
When you want to remove the file, you can use setTrashed of Class File or the method of "Files: delete" in Drive API.
And, at blob = Utilities.newBlob(JSON.stringify(jsonArray), "application/vnd.google-apps.script+json");, when you want to give the mimeType, please use application/json.
When above points are reflected to your script, it becomes as follows.
Modified script:
From:
var folder = DriveApp.getFoldersByName('JSON_EXPFILES').next();
fileSets = {
title: 'exp_planning.json',
mimeType: 'application/json',
"parents": [
{
"id": folder.getId(),
"kind": "drive#parentReference"
}
]
};
blob = Utilities.newBlob(JSON.stringify(jsonArray), "application/vnd.google-apps.script+json");
file = Drive.Files.insert(fileSets, blob);
To:
var folder = DriveApp.getFoldersByName('JSON_EXPFILES').next();
var filename = 'exp_planning.json';
var files = DriveApp.getFilesByName(filename);
while (files.hasNext()) {
files.next().setTrashed(true);
}
// Drive.Files.emptyTrash(); // If you want to empty the trash box, you can also use this. But when you use this, please be careful this.
fileSets = {
title: filename,
mimeType: 'application/json',
"parents": [
{
"id": folder.getId(),
"kind": "drive#parentReference"
}
]
};
blob = Utilities.newBlob(JSON.stringify(jsonArray), 'application/json');
file = Drive.Files.insert(fileSets, blob);
If you want to empty the trash box, you can also use Drive.Files.emptyTrash(). But when you use this, please be careful this.
Note:
In this modified script, it supposes that jsonArray is the correct value you expect. Please be careful this.
When you want to overwrite the existing file of exp_planning.json, please modify above script of "From:" as follows. In this modification, when the file is existnig, the file is overwritten by blob using the method of "Files: update". Ref
var folder = DriveApp.getFoldersByName('JSON_EXPFILES').next();
var filename = 'exp_planning.json';
var files = DriveApp.getFilesByName(filename);
blob = Utilities.newBlob(JSON.stringify(jsonArray), 'application/json');
if (files.hasNext()) {
file = Drive.Files.update({}, files.next().getId(), blob);
// or DriveApp.getFileById(files.next().getId()).setContent(JSON.stringify(jsonArray));
} else {
fileSets = {
title: filename,
mimeType: 'application/json',
"parents": [
{
"id": folder.getId(),
"kind": "drive#parentReference"
}
]
};
file = Drive.Files.insert(fileSets, blob);
}
References:
setTrashed(trashed)
Files: delete

Optimize Google Scripts - Triggers not working

Problem
My Google Script triggers aren't running because it "uses to much CPU time", according to error emails I receive. How can I optimize my scripts to use less CPU time?
I've separated sortGsheetFiles into different trigger, but it still uses to much time. It used to be combined with the importXLSXtoGsheet function.
Scripts explained
I've got 52 folders, each containing one spreadsheet file.
Each folder is shared with different colleagues.
During the day, people make changes to the files.
At the end of the day, all files are collected in one folder (gsheetFolder) and converted to XLSX files, using the function collectAndExportXLS.
These files are copied to a local server in the evening (using batch script and drive sync) which updates other information in the file and are copied back to the importXLSXfolder.
In the morning the importXLSXtoGsheet function runs and converts all XLSX files in the importXLSXfolder folder to Gsheet files in the gsheetFolder.
After that sortGsheetFiles runs, sorting and moving every Gsheet file in one of the 52 folders (using an array list from the current spreadsheet).
Other actions include cleaning the folders with the deleteFolder function.
Triggers
importXLSXtoGsheet - every day - between 6 am and 7 am
sortGsheetFiles - every day - between 7 am and 8 am
collectAndExportXLS - every day - between 10 pm and 11 pm
Script
var gsheetFolder = 'xxx';
var XLSXfolder = 'xxxxx';
var importXLSXfolder = 'xxxxx';
function checkEmptyFolder() {
var folders = DocsList.getAllFolders()
for(n=0;n<folders.length;++n){
if(folders[n].getFiles().length==0 && folders[n].getFolders().length==0){
folders[n].setTrashed(true)
Logger.log(folders[n].getName())
}
}
}
function importXLSXtoGsheet(){
// ========= convert all XLS files in XLS folder to GSheet and put in the general gsheet folder - after that sort in gsheet filiaal folders =========
// cleanup exportXLS folder first
deleteFolder(XLSXfolder);
var files = DriveApp.getFolderById(importXLSXfolder).searchFiles('title contains ".xlsx"');
while(files.hasNext()) {
var xFile = files.next();
var name = xFile.getName();
if (name.indexOf('.xlsx')) {
var ID = xFile.getId();
var xBlob = xFile.getBlob();
var newFile = {
title : name + ('.xlsx'),
key : ID,
parents: [{"id": gsheetFolder}]
}
file = Drive.Files.insert(newFile, xBlob, {convert: true});
}
}
deleteFolder(importXLSXfolder);
}
function sortGsheetFiles() {
// ========= sort Gsheet folder and move to corresponding filiaal folders =========
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var myArrayFileName = sheet.getRange("A2:A53").getValues();
var myArrayFolderId = sheet.getRange("B2:B53").getValues();
var a = myArrayFileName.join().split(',').filter(Boolean);
var b = myArrayFolderId.join().split(',').filter(Boolean);
var folderId = gsheetFolder;
// Log the name of every file in the folder.
var files = DriveApp.getFolderById(folderId).getFiles();
while (files.hasNext()) {
var file = files.next();
for (var i in a) {
var id = file.getId();
if (file.getName() == a[i]) {
moveFiles(id, b[i]); // Match found and move to corresponding folder
}
}
}
deleteFolder(importXLSXfolder);
}
function collectAndExportXLS() {
// ========= collect all Gsheet files, copy to gsheet folder and convert to xlsx and move to xlsx folder =========
// cleanup gsheet folder
deleteFolder(gsheetFolder);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var myArrayFileName = sheet.getRange("A2:A53").getValues();
var myArrayFolderId = sheet.getRange("B2:B53").getValues();
var a = myArrayFileName.join().split(',').filter(Boolean);
var b = myArrayFolderId.join().split(',').filter(Boolean);
var folderId = gsheetFolder;
for (var i in b) {
var files = DriveApp.getFolderById(b[i]).getFiles();
while (files.hasNext()) {
var file = files.next();
var id = file.getId();
moveFiles(id , folderId);
}
}
ConvertBackToXLS()
deleteFolder(gsheetFolder);
}
function moveFiles(sourceFileId, targetFolderId) {
var file = DriveApp.getFileById(sourceFileId);
file.getParents().next().removeFile(file);
DriveApp.getFolderById(targetFolderId).addFile(file);
}
function deleteFolder(folder) {
//delete files in a folder without sending to trash!
var eachFile, idToDLET, myFolder, rtrnFromDLET, thisFile, files;
files = DriveApp.getFolderById(folder).getFiles();
while (files.hasNext()) {//If there is another element in the iterator
eachFile = files.next();
idToDLET = eachFile.getId();
//Logger.log('idToDLET: ' + idToDLET);
rtrnFromDLET = Drive.Files.remove(idToDLET);
};
Logger.log('folder deleted');
}
function ConvertBackToXLS() {
// Log the name of every file in the folder.
var files = DriveApp.getFolderById(gsheetFolder).getFiles();
var dir = DriveApp.getFolderById(XLSXfolder);
while (files.hasNext()) {
try {
var file = files.next();
var ss = SpreadsheetApp.openById(file.getId());
Logger.log(file.getId());
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + file.getId() + "&exportFormat=xlsx";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName());
var newfile = dir.createFile(blob);
} catch (f) {
Logger.log(f.toString());
}
}
}
How about this modification? Please think of this as just one of several answers.
And as an important point, please test the script using a test situation, before you run with your actual situation.
About your script:
collectAndExportXLS(): Abou this function name, I didn't modify collectAndExportXLS(). Because I thought that you might be using this function name at other script or triggers.
Delete all files in gsheetFolder.
Convert a Google Spreadsheet in each folder ID retrieved from "B2:B53" of the sheet with the 1st index in the active Spreadsheet to XLSX format.
Filename is like sample.xlsx.
All converted files are put in XLSXfolder.
Delete all files in all folder IDs.
XLSX files in XLSXfolder are put in importXLSXfolder by other script.
importXLSXtoGsheet(): Abou this function name, I didn't modify collectAndExportXLS(). Because I thought that you might be using this function name at other script or triggers.
Delete all files in XLSXfolder.
Convert all XLSX files in importXLSXfolder to Google Spreadsheet.
Filename is like sample.xlsx.
Converted Google Spreadsheets are put in gsheetFolder.
Delete all files in importXLSXfolder.
sortGsheetFiles()
Move Google Spreadsheets in gsheetFolder to each folder ID retrieved from "B2:B53" of the sheet with the 1st index in the active Spreadsheet.
In order to match the folder ID, the filenames of Google Spreadsheet and the values retrieved from "A2:A53".
Delete all files in importXLSXfolder.
I understood that from your question, the filenames of column "A2:A53" of the active Spreadsheet are the same with the filenames of Google Spreadsheets which were put in the folders of folder IDs of the column "B2:B53".
I understood that the number of all files is less than 100.
I understand like above. If my understanding is correct, how about this modification? In my modification, I used the Batch request of Drive API and the fetchAll method of UrlFetchApp with the type of multipart/form-data for your situation. The batch request and fetchAll method can work with the asynchronous process. By this, I thought that your process cost might be reduced.
In order to use these methods, I used 2 GAS libraries. Before you run the script, please install these 2 libraries for your script. You can see how to install the library as follows.
Install a library for running the fetchAll method of UrlFetchApp with the type of multipart/form-data.
Install a library for running batch request.
Modification points:
collectAndExportXLS()
File IDs in each folder are retrieved by the batch request.
Blobs (XLSX format) from each file ID are retrieved by the fetchAll method of UrlFetchApp.
Files of XLSX format are created by FetchApp.
importXLSXtoGsheet()
File list is retrieved by the files.list method of Drive API.
Files of XLSX format are converted to Google Spreadsheet by the batch request.
sortGsheetFiles()
File list is retrieved by the files.list method of Drive API.
Files of Google Spreadsheet are moved to each folder ID retrieved from the column "B2:B53" of the active Spreadsheet using the batch request.
deleteFolder()
Files in the folder are deleted by the batch request.
When above points are reflected to your script, it becomes as follows.
Modified script:
After installed 2 libraries, please run the following script.
var gsheetFolder = '###';
var XLSXfolder = '###';
var importXLSXfolder = '###';
// Modified
function deleteFolder(folderId) {
var url = "https://www.googleapis.com/drive/v3/files?q='" + folderId + "'+in+parents+and+trashed%3Dfalse&fields=files%2Fid&access_token=" + ScriptApp.getOAuthToken();
var res = UrlFetchApp.fetch(url);
var obj = JSON.parse(res.getContentText());
var reqs = obj.files.map(function(e) {return {method: "DELETE", endpoint: "https://www.googleapis.com/drive/v3/files/" + e.id}});
var requests = {batchPath: "batch/drive/v3", requests: reqs};
if (requests.requests.length > 0) BatchRequest.Do(requests);
}
// Added
function deleteFiles(files) {
var reqs = files.map(function(e) {return {method: "DELETE", endpoint: "https://www.googleapis.com/drive/v3/files/" + e.id}});
var requests = {batchPath: "batch/drive/v3", requests: reqs};
if (requests.requests.length > 0) BatchRequest.Do(requests);
}
// Added
function getValuesFromSpreadsheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
return sheet.getRange("A2:B53").getValues();
}
// Modified
function sortGsheetFiles() {
var url = "https://www.googleapis.com/drive/v3/files?q='" + gsheetFolder + "'+in+parents+and+mimeType%3D'" + MimeType.GOOGLE_SHEETS + "'+and+trashed%3Dfalse&fields=files(id%2Cname)&access_token=" + ScriptApp.getOAuthToken();
var res = UrlFetchApp.fetch(url);
var obj = JSON.parse(res.getContentText());
var values = getValuesFromSpreadsheet();
var reqs = values.reduce(function(ar, e) {
for (var i = 0; i < obj.files.length; i++) {
if (obj.files[i].name == e[0]) {
ar.push({
method: "PATCH",
endpoint: "https://www.googleapis.com/drive/v3/files/" + obj.files[i].id + "?addParents=" + e[1] + "&removeParents=" + gsheetFolder,
});
break;
}
}
return ar;
}, []);
var requests = {batchPath: "batch/drive/v3", requests: reqs};
if (requests.requests.length > 0) BatchRequest.Do(requests);
deleteFolder(importXLSXfolder);
}
// Modified
function importXLSXtoGsheet(){
deleteFolder(XLSXfolder);
var url = "https://www.googleapis.com/drive/v3/files?q='" + importXLSXfolder + "'+in+parents+and+mimeType%3D'" + MimeType.MICROSOFT_EXCEL + "'+and+trashed%3Dfalse&fields=files(id%2Cname)&access_token=" + ScriptApp.getOAuthToken();
var res = UrlFetchApp.fetch(url);
var obj = JSON.parse(res.getContentText());
var reqs = obj.files.map(function(e) {return {
method: "POST",
endpoint: "https://www.googleapis.com/drive/v3/files/" + e.id + "/copy",
requestBody: {mimeType: MimeType.GOOGLE_SHEETS, name: e.name + ".xlsx", parents: [gsheetFolder]},
}
});
var requests = {batchPath: "batch/drive/v3", requests: reqs};
if (requests.requests.length > 0) BatchRequest.Do(requests);
deleteFolder(importXLSXfolder);
}
// Modified
function ConvertBackToXLS(fileList) {
var token = ScriptApp.getOAuthToken();
var reqs1 = fileList.map(function(e) {return {
method: "GET",
url: "https://docs.google.com/spreadsheets/export?id=" + e.id + "&exportFormat=xlsx&access_token=" + token,
}
});
var res = UrlFetchApp.fetchAll(reqs1);
var reqs2 = res.map(function(e, i) {
var metadata = {name: fileList[i].name, parents: [XLSXfolder]};
var form = FetchApp.createFormData(); // Create form data
form.append("metadata", Utilities.newBlob(JSON.stringify(metadata), "application/json"));
form.append("file", e.getBlob());
var url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart";
return {url: url, method: "POST", headers: {Authorization: "Bearer " + token}, body: form};
});
FetchApp.fetchAll(reqs2);
}
// Modified
function collectAndExportXLS() {
deleteFolder(gsheetFolder);
var values = getValuesFromSpreadsheet();
var reqs1 = values.reduce(function(ar, e) {
if (e[0] && e[1]) {
ar.push({
method: "GET",
endpoint: "https://www.googleapis.com/drive/v3/files?q='" + e[1] + "'+in+parents+and+trashed%3Dfalse&fields=files(id%2Cname)",
});
}
return ar;
}, []);
var resForReq1 = BatchRequest.Do({batchPath: "batch/drive/v3", requests: reqs1});
var temp = resForReq1.getContentText().split("--batch");
var files = temp.slice(1, temp.length - 1).map(function(e) {return JSON.parse(e.match(/{[\S\s]+}/g)[0])});
var fileList = files.reduce(function(ar, e) {return ar.concat(e.files.map(function(f) {return f}))}, []);
ConvertBackToXLS(fileList);
deleteFiles(fileList);
}
Note:
In this modification, the error handling is not reflected, because I couldn't test your situation. So please add it, if you are required.
If the file size of XLSX files is large, the error might occur.
References:
Batch request of Drive API
BatchRequest
FetchApp

Unauthorized error 401 using UrlFetchApp

I am trying to create a webapp, part of which will allow the user to create a new spreadsheet file in my drive. The fileURL is a link to an excel file ( download link taken from a file cabinet).
I am struggling with passing authority so that a google spreadsheet can be created. I am getting an unauthorized error 401. I had read that having DriveApp.getRootFolder() adds the Drive scope, but I am going wrong somewhere.
function downloadFile(fileURL, folder) {
var filename = fileURL.match(".+/(.+?)([\?#;].*)?$")[1];
var auth = ScriptApp.getOAuthToken();
var header = {"authorization": "Bearer " + auth};
var params = { 'method':'post', 'headers':header, 'muteHttpExceptions':true};
var holder = DriveApp.getRootFolder();
var response = UrlFetchApp.fetch(fileURL, params);
var rc = response.getResponseCode();
var blob = response.getBlob();
//delete file if it already exists
var fileList = DriveApp.getFilesByName(filename);
while (fileList.hasNext()) {
var fileId = fileList.next().getId();
DriveApp.getFileById(fileId).setTrashed(true);
}
var resource = {
"mimeType": "application/vnd.google-apps.spreadsheet",
"parents": [{id: folder}],
"title": filename
}
//Create file
var res = Drive.Files.insert(resource, blob); //put
}