Move submitted files in drive to another folder - javascript

I'm trying to send a submitted images to unique subfolder any time some user send images through my google form, this is my code so far :
var idnumber = Utilities.formatDate(new Date(), 'America/Bogota', 'ddMMyyyyHHmmss')
function onFormSubmit(e) {
var driveMainFolder = 'MyFolder'
var driveSubFolder = idnumber;
// Create subfolder
var parentFolder = DriveApp.getFoldersByName(driveMainFolder).next();
var newFolder = parentFolder.createFolder(driveSubFolder);
// Move files to subfolder
var files = DriveApp.getFoldersByName(driveMainFolder).next().getFiles();
while (files.hasNext()) {
var file = files.next();
var destination = DriveApp.getFoldersByName(driveSubFolder).next();
destination.addFile(file);
var pull = DriveApp.getFoldersByName(driveMainFolder).next();
pull.removeFile(file);
}
}
It kind of works, after sending the images some of these images stay in "MyFolder" instead of moving directly to the unique subfolder.
This trigger is being called in the event OnFormSubmit, is created in the Google Form Spreadsheet.
In "my Executions" the trigger doesn't display anything wrong but not the whole images moves to unique subfolder.
I'm sending 5 images, in average each one has 18kb.
Is there a way to upload images from a Google Form and add a trigger to organize the images ? Thanks !

Related

How to save input file type information in sessionStorage?

I have this code for file saving browsing, specifically image..
I'm aware that you can't set file programmatically, you have to go to folder popups in order to select file for security reason. So my problem is, I want the file to be saved in sessionStorage so that when the users reload the page, they don't need to reselect the image.
I'm doing this approach..
var fileInput = document.getElementById('file');
sessionStorage.input = JSON.stringify(fileInput);
But when I reload the page, it's not working anymore with..
formData.append(fileInput.files[0].name, sessionStorage.input);
I tried to do console.log(sessionStorage.inputFile) but it only printed '[object File]'
You can use below code to save image data in session storage
var file = element.files[0];
var reader = new FileReader()
reader.onload = function(base64) {
localStorage["file"] = base64;
}
//Store it in session storage
var img_base64 = localStorage["file"];
var base64_arr = img_base64_data.split(",");
var img_format = base64_arr[0].split(";")[1];
var img_content = base64_arr[1];
var file = new File([img_content], "<file name>", {type: img_format});
// get file as file.files[0] and store it in session storage

Google script to move audio ".wav" files from one folder to another

So I need to move audio files that are dumped via a submission form into more specific folders. I have about 10 folders in all That I need to move them to. Here's the ask...
Collect the Audio files from the submission folder
Sort them into their appropriate folders based on key words in the file name
Here's the code I have so far.
function moveFiles(source, target) {
var sourceFolder = DriveApp.getFolderById('source');
var targetFolder = DriveApp.getFolderById('target')
var files = sourceFolder.getFilesByType(Mimetype);
while (files.hasNext()) {
var file = files.next();
targetFolder.addFile(file);
file.getParents().next().removeFile(file);
}
}
I do not know the Mimetype for audio/wav or if it is supported in google scripts.
any help is appreciated.

Insert image from Google drive into sheet

I'm trying to insert image into sheet. However, it keeps return Error retrieving image from URL or bad URL. The webContentLink method works normally. It return a link with &export=download. I even tried to truncate that and insert image but still get the same error. Many of the image files have the public-anyone can see sharing setting.
I have tried many ways to insert image but none is working. Some answers about this were about 3-4 years ago so I just have to ask again to make sure. I have tried function IMAGE in sheet but it often load the image very slowly (often 10s of minutes after entering the function). I also tried blob method but to no avail. It returns the strange error that I don't know how to handle a server error occurred. The function works normally for other files, working with files in Google Drive is very very difficult. I am at my wit's end, please help.
function insertImg()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var currentCell = sheet.getActiveCell();
var thisFileId = SpreadsheetApp.getActive().getId();
var thisFile = DriveApp.getFileById(thisFileId);
var folder = thisFile.getParents().next();
var files = folder.getFiles();
var i =0;
while (files.hasNext())
{
var file = files.next();
if (file.getMimeType()== 'image/jpeg')
{
i++;
var img = Drive.Files.get(file.getId()).webContentLink;
sheet.insertImage(img, 1, i);
}
}
}

Using Google Chrome extensions to import/export JSON files?

I'm creating a Google Chrome extension at the moment and I was wondering if it's possible for it to both create JSON files to download (export) and create a button where users can make the extension open and parse JSON files that they have saved in their local file system or on a USB stick (import)?
The parsing of each JSON from the local file system would simply involve reading off each key-value pair and doing something with the data. It would only have to deal with strings, so nothing complicated.
**EDIT: **My question is not a duplicate of this one because I'm not interested in changing the user's download path. All I want is to enable them to, with their consent, download a file to their normal download directory (which Filesaver.js can do). Plus, that post says nothing about importing.
You can fake link to "download" imaginary array MyData or whatever,:
var MyArray = [elem1, elem2, ....];
var _myArray = JSON.stringify(MyArray , null, 4); //indentation in json format, human readable
var vLink = document.createElement('a'),
vBlob = new Blob([_myArray], {type: "octet/stream"}),
vName = 'watever_you_like_to_call_it.json',
vUrl = window.URL.createObjectURL(vBlob);
vLink.setAttribute('href', vUrl);
vLink.setAttribute('download', vName );
vLink.click();
this will export/download your array into json file named as vName variable.
If you wish to import/read file:
create input element (type=file) and make it invisible (here I'm having html element and then adding js listener in script)
<input type="file" id="importOrig" accept=".json" style="display:none"/>
script
importOrig.addEventListener("change", importFun, false);
make button fakeImp (or any element), that you can style as you wish and that will be used as trigger for importing event
fakeImp.onclick = function () {importOrig.click()}
import function (from listener)
function importFun(e) {
var files = e.target.files, reader = new FileReader();
reader.onload = _imp;
reader.readAsText(files[0]);
}
function _imp() {
var _myImportedData = JSON.parse(this.result);
//here is your imported data, and from here you should know what to do with it (save it to some storage, etc.)
......
importOrig.value = ''; //make sure to clear input value after every import
}

Javascript & HTML File API- can a javascript object based on a file object still contain the file's location?

Say I have an array of user selected files.
In my application, each selected file corresponds to a person. Once the user selects the files, a table appears. In the left column is each file's name. In the right hand column, the user must fill in the name of the relevant person. Once all the names are filled in the user can upload the files. As there could be hundreds of names to fill in, I would like to be able to save the user's progress to localStorage periodically, in case the page refreshes.
I can pass each file object (var thisFile) to an uploading script and the browser will know where to locate the file.
However, I would like to be able to save the list of selected files in localStorage, and JSON.stringify will strip out a file object.
So say I first create a javascript object based on the file object (var file below).
If I then pass var file to the uploading script, will the browser still be able to locate the file, or would the full path to the file have been lost?
for (var i = 0; i < userSelectedFiles.length; i++) {
//File object (Stripped out by JSON.stringify).
var thisFile = userSelectedFiles[i];
//Create a javascript object based on the file object (Not stripped out by JSON.stringify).
var file: {
'lastModified': thisFile.lastModified,
'lastModifiedDate': thisFile.lastModifiedDate,
'name': thisFile.name,
'size': thisFile.size,
'type': thisFile.type
},
}
After more research, I have found that a file must be reselected after a browser refresh- the location of a file cannot be stored in localStorage.
You can save files to offline storage.
Read this article about offline storage offline_storage and quota-research
Read documentation LocalFileSystem
You can test offline storage here test page
How to use link
Here is the example for WebKit browsers (chrome and opera) of creating a file -> info.txt with your content, you need to ask a user of storage quota, in this example, is 10mb.
var maxSize = 1024 * 1024 * 10;
var onError = function() {};
var requestFs = window.requestFileSystem ||
window.webkitRequestFileSystem ||
window.mozRequestFileSystem ||
window.msRequestFileSystem || undefined;
var onRequest = function(grantedSize) {
requestFs(window.PERSISTENT, grantedSize, function(filesystem) {
filesystem.root.getFile("info.txt", {create: true}, function(DatFile) {
DatFile.createWriter(function(DatContent) {
var blob = /** your file or blob*/;
DatContent.write(blob);
});
});
}, onError)
};
navigator.webkitPersistentStorage.requestQuota(maxSize, onRequest, onError);

Categories

Resources