how can I get path of file from input api - javascript

hy users
I try to get the path of a file via html5 js
I try:
jQuery("#pfad").change(function(evt){
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
for (var i = 0; i < files.length; i++) {
alert(files[i].path);
}
but path isn't a attribute of this file object....
what can i do?

You can't get the full file path due to security limitations. However you can read the name of the file:
jQuery("#pfad").change(function (evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
for (var i = 0; i < files.length; i++) {
console.log(files[i].name);
}
});

Most browsers dont allow to get the full file path on client side. But in case of Google Chrome and Mozilla Firefox you can get the path by:
jQuery("#pfad").change(function(evt){
var path = $(this).val();
alert(path);
}
I tested it on both of these browsers.

Related

Passing a JSON object from the background script to the content script in a chrome extension

I have a JS array in the "background.js" file of my Chrome extension. I converted the JS object to a JSON string to pass it into the "content.js" file but am unable to do so.
Can I be helped with the code to send the JSON object from the "background.js" file and the code to receive the same from the "content.js" file.
// This is the important portion of the code present in the background.js file.
console.log("Inside the buttonClicked function");
var titles = [];
var hrefs = [];
var links = document.getElementsByClassName('uqZtlf x0HGk QRiHXd MymH0d maXJsd');
for (var i = 0; i < links.length; i++)
{
hrefs.push(links[i].href); // capturing urls
titles.push(links[i].title); // capturing titles
}
jsonObjectLinks = JSON.stringify(hrefs); // converting the js object to the JSON string
console.log(jsonObjectLinks);
var jsonObjectTitles = JSON.stringify(titles);
// I now wish to pass on the jsonObjectTitles to the content.js file

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.

jQuery move local files to another directory

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

Exporting table data from HTML page to CSV file using the Browser Console (Chrome)

I need to extract some data from a web page and store it in a CSV file to be opened in Excel. I am trying to do this from the browser console, but I am getting a non-defined error.
So far I've tried using this code to export the table:
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV file
downloadCSV(csv.join("\n"), filename);
}
When I define this function and run it, I get a "downloadCSV not defined error". Are there any limitations to the built in Browser console in Chrome, besides the obvious ones?
This code also needs to be run in a loop, since there are multiple pages with tables, but it would be nice to have it all located in a single CSV file. For starters it should really just extract anything it can find in the table. I'll dive in and extract the specific fields I need later when I get this working.
Edit:
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
csvFile = new Blob([csv], {
type: "text/csv"
});
downloadLink = document.createElement("a");
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
What you could do is, instead of creating a csv for every table, to save all the data from the pages to some storage, like for example the local storage:
$(document).ready(function() {
$(window).unload(saveSettings);
loadlist();
});
function loadlist() {
savedlist = localStorage.list;
}
function savelist() {
localStorage.list = savedlist + currentlist;
}
Instead of immediately downloading the csv, collect all your data in the storage using the examples above (you will need to adjust them to your needs). Then, once you have all data, put it into a single csv and then download this. Afterwards, delete the data from the storage:
function deletelist() {
localStorage.removeItem(list);
}
The local storage persists across your pages from the same domain, until cleared by you or when the user deletes his browser data manually.

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);

Categories

Resources