Modify this script to upload all files from google forms response to one folder in google drive - forms

I found this script that will upload files from google forms response to a folder using the first response (name of applicant) to name the folder.
function onFormSubmit(e) {
const folderId = "###"; // ID of the destination folder
const form = FormApp.getActiveForm();
const formResponses = form.getResponses();
const itemResponses = formResponses[formResponses.length - 1].getItemResponses();
// Prepare the folder.
const destFolder = DriveApp.getFolderById(folderId);
const folderName = itemResponses[0].getResponse();
Logger.log(folderName)
const subFolder = destFolder.getFoldersByName(folderName);
const folder = subFolder.hasNext() ? subFolder.next() : destFolder.createFolder(folderName);
// Move files to the folder.
itemResponses[1].getResponse().forEach(id => DriveApp.getFileById(id).moveTo(folder));
}
I tried using it but it will only upload one file - the one correspnding to the specific question number in the line itemResponses[1].getResponse()
How Do i modify this script so it will upload all of the files in the response regardless of their position without creating multiple folders?
i.e. is it possible to set a range of questions that all the files will upload?
Also, i want to modify the script so that name of the folder will also consist of the response sequence number as a prefix to the name of responder, how is that possible?

Related

how to save data on csv file with flutter?

I have data come from a device to my flutter application via bluetooth.
I have lists that are displayed one by one on alerts. I want to collect data on all the alerts and then save it on csv file.
The problem is that there are lot of files created and every file contain juste one list this mean that for every alert there is a file created.
this is the code:
setupMode.generateCsv((message) async {
List<List<String>> data = [
["No.", "X", " Y", "Z", "Z"],
[message.data[1], message.data[2], message.data[3], message.data[4]],
];
String csvData = ListToCsvConverter().convert(data);
final String directory = (await getApplicationSupportDirectory()).path;
final path = "$directory/csv-${DateTime.now()}.csv";
print(path);
final File file = File(path);
await file.writeAsString(csvData);
print("file saved");
print(csvData.length);
});
}
I want to collect all the data and store it on one file.
In order to write into one file, there are two things you need to change:
File name:
final path = "$directory/csv-${DateTime.now()}.csv";
This creates a new file every time you call it. You should use the same file name, e.g.:
final path = "$directory/csv-alert-data.csv";
The second change is the write type:
await file.writeAsString(csvData,mode:FileMode.append);
This will append the new data to the end of the existing CSV file.

google apps script: file.setOwner() Not Transferring Ownership in Google Drive

I am trying to transfer ownership of all my .pdf files to another account with more space. I am testing the code with a single folder in my drive.
function transfer() {
var user = Session.getActiveUser();
var folder = DriveApp.getFolderById('123folder-id456789-VxdZjULVQkPAaJ');
var files = folder.getFilesByType(MimeType.PDF);
while (files.hasNext()) {
var file = files.next();
if (file.getOwner() == user) file.setOwner('example#gmail.com');
}
}
When I run the code, none of the files change ownership.
How about this modification?
Modification points:
In your script, it tries to compare the objects of Session.getActiveUser() and file.getOwner(). I think that this is the reason of your issue.
So how about this modification? Please think of this as just one of several answers.
Modified script:
function transfer() {
var user = Session.getActiveUser().getEmail(); // Modified
var folder = DriveApp.getFolderById('123folder-id456789-VxdZjULVQkPAaJ');
var files = folder.getFilesByType(MimeType.PDF);
while (files.hasNext()) {
var file = files.next();
if (file.getOwner().getEmail() == user) file.setOwner('example#gmail.com'); // Modified
}
}
In this modification, the emails are compared.
References:
getActiveUser()
getOwner()
Class User
If this didn't resolve your issue, I apologize.
Currently drive can't transefere the ownership of file that are not build-in, like pdf, zip, etc. So you must download them and reupload from the other account. I wrote a colab to do that without consume my bandwith. It can recursively transfere an entire folder with both build-in file types and other file types.

Saving screenshots with protractor

I'm attempting to save a screenshot using a generic method in protractor. Two features, it creates the folder if it does not exist and it saves the file (with certain conditions).
export function WriteScreenShot(data: string, filename: string) {
let datetime = moment().format('YYYYMMDD-hhmmss');
filename = `../../../test-reports/${filename}.${datetime}.png`;
let path =filename.substring(0, filename.lastIndexOf('/'));
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
let stream = fs.createWriteStream(filename);
stream.write(new Buffer(data, 'base64'));
stream.end();
}
This can be used by calling browser.takeScreenshot().then(png => WriteScreenShot(png, 'login/login-page')); Using this example call, a file will be created, I assumed, in the path relative where my WriteScreenShot method's file resides. But that does not appear to be the case.
For example, when I run my spec test in the spec's folder, the image gets saved in the correct place. But if I run it at the project root, an error is capture. Obviously, this has to do with my relative path reference. How do I capture the project's root directory and build from that so that I can run the test from any directory?
This is a classical directory access error. Let me just explain what is happening to your code -
let path =filename.substring(0, filename.lastIndexOf('/'));
The above line outputs to ../../../test-reports
fs.existsSync checks whether thispath exists or not -
case 1 :(postive flow) Your spec folder is in the same current working directory in which you are trying to create reports folder. When you run your test, the path exists, it generates the test-reports directory & screenshots and your code works fine.
case 2:(negative flow) When you try to run it from the root directory which is the current working directory now, fs.existsSync tries to check the path & the reports folder inside it. If it doesn't exist , fs.mkdirSync tries to create your directories but it would fail as it cannot create multiple directories.
You should be using native path module of nodejs to extract the path instead of using file substring and the mkdirp external module for creating multiple directories.
import * as path from 'path';
let {mkdirp} = require('mkdirp'); // npm i -D mkdirp
export function WriteScreenShot(data: string, filename: string) {
let datetime = moment().format('YYYYMMDD-hhmmss');
filename = `../../../test-reports/${filename}.${datetime}.png`;
let filePath = path.dirname(filename); // output: '../../..' (relative path)
// or
let filePath = path.resolve(__dirname); // output: 'your_root_dir_path' (absolute path)
// or
let filePath = path.resolve('.'); // output: 'your_root_dir_path' (absolute path)
if (!fs.existsSync(filePath )) {
mkdirp.sync(filePath); // creates multiple folders if they don't exist
}
let stream = fs.createWriteStream(filename);
stream.write(new Buffer(data, 'base64'));
stream.end();
}
If you are curious to know the difference btw mkdir & mkdir-p please read this SO thread.

Upload Servlet with custom file keys

I have built a Server that you can upload files to and download, using Eclipse, servlet and jsp, it's all very new to me. (more info).
Currently the upload system works with the file's name. I want to programmatically assign each file a random key. And with that key the user can download the file. That means saving the data in a config file or something like : test.txt(file) fdjrke432(filekey). And when the user inputs the filekey the servlet will pass the file for download.
I have tried using a random string generator and renameTo(), for this. But it doesn't work the first time, only when I upload the same file again does it work. And this system is flawed, the user will receive the file "fdjrke432" instead of test.txt, their content is the same but you can see the problem.
Any thoughts, suggestions or solutions for my problem?
Well Sebek, I'm glad you asked!! This is quite an interesting one, there is no MAGIC way to do this. The answer is indeed to rename the file you uploaded. But I suggest adding the random string before the name of the file; like : fdjrke432test.txt.
Try this:
filekey= RenameRandom();
File renamedUploadFile = new File(uploadFolder + File.separator+ filekey+ fileName);
item.write(renamedUploadFile);
//remember to give the user the filekey
with
public String RenameRandom()
{
final int LENGTH = 8;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random()*26)+97));
}
System.out.println(sb.toString());
return sb.toString();
}
To delete or download the file from the server you will need to locate it, the user will input the key, you just need to search the upload folder for a file that begins with that key:
filekey= request.getParameter("filekey");
File f = new File(getServletContext().getRealPath("") + File.separator+"data");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filekey);
}
});
String newfilename = matchingFiles[0].getName();
// now delete or download newfilename

How to read a directory with using InputStream in eclipse plugin developement

I'm developing an eclipse plug-in and I need to traverse a directory and whole content of the directory. I found the method which reads a file in plug-in (bundleresource) as InputStream.
InputStream stream = Activator.class.getResourceAsStream("/dir1/dir2/file.ext");
this method works for files only. I need a way to read directories, list subdirectories and files like File.io.
Thanks.
Do you want to read a resource directory of your plugin? Otherwise you have to traverse a directory and open one stream per file:
String path = "c:\\temp\\";
File directory = new File(path);
if (directory.isDirectory()) {
String[] list = directory.list();
for (String entry : list) {
String absolutePath = path + entry;
System.out.println("processing " + absolutePath);
File file = new File(absolutePath);
if (file.isFile()) {
FileInputStream stream = new FileInputStream(file);
// use stream
stream.close();
}
}
}
If you want to traverse subdirectories as well you should wrap this into a recursive method, check if file is a directory and call the recursive method in this case.