jQuery move local files to another directory - javascript

I would like to create a function which will count the files from a directory.
If there are 5 files, move the oldest file to another directory.
I found a code sample, but it is not working for my case.
var myFileList = Folder("C:/Test").getFiles();
var folderCount = GetFoldersCount(myFileList) ;
$.writeln(folderCount);
function GetFoldersCount(fileList) {
var folderCount = 0;
console.log(folderCount);
for (var i = 0; i < fileList.length; i++) {
var myFile = myFileList[i];
if (myFile instanceof Folder)
folderCount++;
}
return folderCount
}
I am getting the error "Folder" is not defined.

Its impossible directly access local files by JS for seccurity issue.
Another thing is that you can access files on drive over Ajax call and process
on response. Using Ajax you can send request what you want to do it on background.
You used example at InDesign forum. I dont know InDesign but I am not sure that it will work.
Otherwise look for documentation about HTML5 File API. Hope that you will find answer.
https://w3c.github.io/FileAPI/
some examples:
https://www.html5rocks.com/en/tutorials/file/dndfiles/

I found out the solution for this task, which works perfect for me.
I call the function with the initial directory:
moveErrorFiles('C:\\Folder1');
And below are the 2 simple functions I use.
function moveErrorFiles(fileDir) {
var fileSysObj, file, folder, fileCounter, currentFile;
var fileMumber = 0;
fileSysObj = new ActiveXObject("Scripting.FileSystemObject");
folder = fileSysObj.GetFolder(fileDir);
fileCounter = new Enumerator(folder.files);
for (; !fileCounter.atEnd(); fileCounter.moveNext()) {
currentFile = fileCounter.item();
fileMumber++;
if (fileMumber > 5) {
moveFile(currentFile);
}
}
} //function moveErrorFiles() ends here
function moveFile(fileToMove) {
var object = new ActiveXObject("Scripting.FileSystemObject");
var file = object.GetFile(fileToMove);
file.Move("C:\\Folder2\\");
console.log("File was moved successfully");
} //function moveFile() ends here

Related

Google Script - Compare part of a file name to a subfolders name and move file to subfolder if there is a match

Thanks to the awesome people on here I have a script that is cross checking file names with folder names and moving the file to the folder if the name matches (code below)
What I'm struggling with now if searching the subfolder of a certain folder and checking the files to see if part of the name matches the subfolder name
e.g
Folders:
Folder name: example1
Subfolder name: example1-commercial
Subfolder name: example1-clients
Files:
example1-commercial.pdf (move to example1-commercial folder)
example1-clients.pdf (move to example1-clients folder)
Any help would be greatly appreciated!
Thanks!
function folderAndFiles(){
var files = [];
var folderMap = {};
var foldersParent = DriveApp.getFoldersByName("names").next();
var filesParent = DriveApp.getFoldersByName("files").next();
var filesIterator = filesParent.getFiles();
var foldersIterator = foldersParent.getFolders();
while(filesIterator.hasNext()) {
var currentFile = filesIterator.next();
files.push(currentFile);
}
while(foldersIterator.hasNext()) {
var currentFolder = foldersIterator.next();
folderMap[currentFolder.getName()] = currentFolder;
}
for (var i=0; i<files.length; i++) {
var file = files[i];
var fileName = file.getName().replace('.jpg', '');
var destinationFolder = folderMap[fileName];
if (destinationFolder) {
destinationFolder.addFile(files[i]);
filesParent.removeFile(file);
Logger.log("Moved");
}
}
}
You can use the following code to accomplish your goals:
function sortFiles() {
// var folders = Drive.Files.list({
// "q": "mimeType = 'application/vnd.google-apps.folder' and trashed = false",
// "fields": "items(title, id)"
// });
var folders = DriveApp.getFolders();
// var files = Drive.Files.list({
// "q": "mimeType != 'application/vnd.google-apps.folder' and trashed = false",
// "fields": "items(title, id)"
// });
var files = DriveApp.getFiles();
var folderIDs = [];
var folderNames = [];
var fileIDs = [];
var fileNames = [];
do {
var folder = folders.next();
folderNames.push(folder.getName());
folderIDs.push(folder.getId());
} while (folders.hasNext());
do {
var file = files.next();
fileNames.push(file.getName());
fileIDs.push(file.getId());
} while (files.hasNext());
for (var i = 0; i < fileNames.length; i++) {
for (var j = 0; j < folderNames.length; j++) {
if (folderNames[j].search(fileNames[i]) > -1) {
var oldFileParents = DriveApp.getFileById(fileIDs[i]).getParents();
DriveApp.getFolderById(folderIDs[j]).addFile(DriveApp.getFileById(
fileIDs[i]));
if (oldFileParents.hasNext()) {
do {
oldFileParents.next().removeFile(DriveApp.getFileById(fileIDs[i]));
} while (oldFileParents.hasNext());
}
}
}
}
}
Based on your comment I have updated the code to only use the DriveApp class and no Drive API. For future reference, I have commented the API calls to the method Files.list that I used to gather every file and folder (except the ones on the recycle bin).
The code will first use the methods .getFolders() and .getFiles() to gather all the folders and files of your Drive. It will later create two arrays per folders and files: one for IDs and other for names. Then, the names array are iterated looking for coincidences. After one coincidence is found, it will record the current folder(s) of the file with the methods .getFileById().getParents(). We need to use this approach because a single file can be inside different folders of Drive.
So the final steps are going to be: first, gather the current folder(s) of the file. After that, we shall include the file into the new folder. And finally, we must delete the parent(s) folder previously saved on the first step.
Please, write back to me again if you need further help or clarifications.

Delete all but x most resent files in a folder Google script

I have a folder where I store backup files and I want to keep only the 5 most recent files
All files are in a folder called New Project Backups
All files have New Project as part of their name
I found this here
Delete old files
How do I focus the Function to look in only the folder New Project Backups
Thanks
function myFunction() {
var file_iterator = DriveApp.getFiles();
var file_list = [];
while (file_iterator.hasNext()) {
var fl = file_iterator.next();
if (fl.getName().match("New Project"))
file_list.push(fl);
}
// Sort the files on date created
file_list = file_list.sort(function(fl1, fl2) {
return fl1.getDateCreated() < fl2.getDateCreated();
});
// Removing uneeded file
while (file_list.length > 5) {
var fl = file_list.pop();
// fl.setTrashed(true); // if you want it in the trash
// instead of fully removed.
DriveApp.removeFile(fl);
}
}
Using DriveApp.getFiles() will get you all files in the drive. you can fix that by replacing
var file_iterator = DriveApp.getFiles();
with
id = "0XrUxpDX-E8dpeE9EQmpYLeplOLB";
var folders = DriveApp.getFolderById(id);
var file_iterator = folders.getFiles();
the id is the folder id you want to work with, you can find it from the folder URL
Example,
Folder URL: https://drive.google.com/drive/u/1/folders/0XrUxpDX-E8dpeE9EQmpYLeplOLB
Folder ID: 0XrUxpDX-E8dpeE9EQmpYLeplOLB
enjoy ;)

How to add to an existing FileList object with JavaScript?

I am creating a drag and drop file upload zone. When I upload multiple files at a time it works but I need it to be able to support uploading in multiple stages. I know that the issue below is that I am setting files each time, but I can't figure out the right way to get more files added to dFiles each time the method is called
var dFiles;
//var dFiles = []
var holder = document.getElementById('holder');
holder.ondrop = function (e) {
e.preventDefault();
dFiles = (e.dataTransfer.files);
//dFiles.push(e.dataTransfer.files);
}
I tried initilaizing dfiles as an empty array and adding the files (commented out above). Later this created a data type mismatch error when I was reading the file data
for (var i = 0; i < dFiles.length; i++) {
reader = new FileReader();
reader.readAsDataUrl(dFiles[i]); //error
}
e.dataTransfer.files is a list of files.
You will have to add each file separately to dFiles:
var files = e.dataTransfer.files;
for (var i = 0, l = files.length; i < l; i++) {
dFiles.push(files[i]);
}
Or the ES6 way:
dFiles.push(...e.dataTransfer.files);

migrate from DocsList to DriveApp

I'm new to google scripts and was able to manipulate some code to work for a project, but it will no longer work as a result of the following:
ReferenceError: "DocsList" is not defined.Dismiss
Here is the code I have:
function report() {
var folder = DocsList.getFolder("FOLDER NAME HERE");
var contents = folder.getFiles();
var file;
var data;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clearContents();
sheet.appendRow(["URL", "Employer"]);
for (var i = 0; i < contents.length; i++) {
file = contents[i];
var qaDate,qaERName
if (file.getFileType()==DocsList.FileType.SPREADSHEET) {
var dataSheet = SpreadsheetApp.open(file).getSheetByName("data");
var configSheet = SpreadsheetApp.open(file).getSheetByName("Config");
I have a few references to DocsList, I've done some digging and cant figure out how to get something similar to getfolder
Let's start with the first line:
var folder = DocsList.getFolder("FOLDER NAME HERE");
If you go to the documentation, and look at all the methods for DriveApp that have anything to do with folders, you'll see four methods:
getFolderById(id)
getFolders()
getFoldersByName(name)
getRootFolder()
There is only one method that will get just one folder, getFolderById(id). If you are getting the same folder every time, and you can easily get the ID, then use that option. If that is not possible, then you can use getFoldersByName(name), but that gets multiple folders. Even though it gets multiple folders, you can easily get just the first folder.
var folders = DriveApp.getFoldersByName('Folder Name');
var folder = folders.next();
Logger.log('folder: ' + folder.getName());
So, start there, and make that change.

Is Parse's Javascript file upload broken?

I've been trying to save a user-uploaded image to parse for the longest time, and nothing seems to work -- even when following their documentation.
Below is the handler I use for the onChange() on a multiple file upload. At first I was concerned about multiple file uploads, but at this point just saving one image doesn't work.
function fileHandler(event) {
var files = event.target.files;
stopPictures = [];
$("#stop-img-container").empty();
if (files[0] != null) {
$("#stop-img-container").show();
for (var i = 0; i < files.length; i++) {
var file = files[i];
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
var image = $("<img/>",{
"title": picFile.name,
"class": "stop-image",
"src": picFile.result
}).appendTo("#stop-img-container");
var name = picFile.name;
var dataFile = picFile.result;
var base64str = dataFile.substring(dataFile.indexOf("base64,")+7,dataFile.length);
var parseFile = new Parse.File(name,{base64:base64str}); // saving logs 404 Not Found from POST to "http://api.parse.com/1/files"
var parseFile = new Parse.File(name,dataFile); // saving logs "Uncaught Creating a Parse.File from a String is not yet supported."
var parseFile = new Parse.File(name,file); // saving logs 404 Not Found from POST to "http://api.parse.com/1/files"
var parseFile = new Parse.File(name,base64str); // saving logs "Uncaught Creating a Parse.File from a String is not yet supported."
parseFile.save().then(function (savedFile) {
stopPictures.push(savedFile);
alert("worked");
});
});
picReader.readAsDataURL(file);
}
} else {
$("#stop-img-container").hide();
}
}
There's some extraneous stuff here, but basically it collects the user's selected files, displays them for them once they've finished loading, and then creates them as a Parse file. I've left it in to show that at least something is working as it properly locally stores and previews the user's selected files.
I have included three different ways of creating the same Parse file. However, all of them fail when I try to save to Parse in any way.
Parse's Javascript API docs says that any of these should work fine. But they lie, or I'm an idiot.
Anyone have any idea why this doesn't seem to work? Seems like a pretty critical aspect of their API is broken completely -- which I find hard to imagine.
EDIT: I'm also positive I'm properly parsing (lower case p) the base64 string as this site confirms the appropriate image and works.
I experienced the same problem.
Finally I found what causes the problem.
It's a "file name".
I suspect the file name in tuckerchapin's example is null.
var name = picFile.name;
I wrote the example with React.
this code works fine.
class ImageUpload extends React.Component {
onChange(e) {
var file = e.target.files[0];
var parseFile = new Parse.File(file.name, file);
Parse.User.current().set("icon",parseFile);
Parse.User.current().save();
}
handleSubmit(e) {
e.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="file" onChange={this.onChange.bind(this)} />
</form>
);
}
}

Categories

Resources