JavaScript: Read files in folder - javascript

EDIT: I'm trying to read all the files in a specific folder and list the files in there, not read the content of a specific file. I just tried to simply create an FileSystemObject and it doesn't do anything either. I show an alert (which pops up) beforfe making the FileSystemObject, and one after it (which isn't shown). So the problem is in simply creating the object.
Original:
I am trying to read all the files in a folder by using JavaScript.
It is a local HTML file, and it will not be on a server, so I can't use PHP I guess.
Now I'm trying to read all the files in a specific given folder, but it doesn't do anything on the point I make a FileSystemObject
Here is the code I use, The alert shows until 2, then it stops.
alert('1');
var myObject, afolder, date;
alert('2');
myObject = new ActiveXObject("Scripting.FileSystemObject");
alert('3');
afolder = myObject.GetFolder("c:\\tmp");
alert('4');
date = afolder.DateLastAccessed;
alert("The folder"+name+" is a temporary folder.");
Am I doing this the right way?
Thanks!

The method I found with a Google search uses HTML5 so if you are using a modern browser you should be good. Also the tutorial page seems to check if the browser you are using supports the features. If so you should be good to follow the tutorial which seems pretty thorough.
http://www.html5rocks.com/en/tutorials/file/dndfiles/

This solution only works on IE11 or older since it is MS based
<script type="text/javascript">
var fso = new ActiveXObject("Scripting.FileSystemObject");
function showFolderFileList(folderspec) {
var s = "";
var f = fso.GetFolder(folderspec);
// recurse subfolders
var subfolders = new Enumerator(f.SubFolders);
for(; !subfolders.atEnd(); subfolders.moveNext()) {
s += ShowFolderFileList((subfolders.item()).path);
}
// display all file path names.
var fc = new Enumerator(f.files);
for (; !fc.atEnd(); fc.moveNext()) {
s += fc.item() + "<br>";
}
return s;
}
function listFiles() {
document.getElementById('files').innerHTML = showFolderFileList('C:');
}
</script>
<input type='button' onclick='listFiles()' value='List Files' />
<div id="files" />

Related

Creating Photoshop Plugin - trying to find simpler way to source file in javascript function

I'm creating a plugin I would like to be used for both Mac and Windows.
As the file trees are different, I would like to find a simpler way to source a file in a function contained in my /host/index.jsx file.
My file is located at /files/thisismyfile.psd
Currently I can only successfully source it by entering the full file tree from the main hard drive:
var fileRef = new File("/Library/Application Support/Adobe/CEP/extensions/com.my.panel/files/thisismyfile.psd");
I would much prefer to use something like:
var fileRef = new File("./files/thisismyfile.psd");
I've also tried testing having the file in each other folder and simply searching for:
var fileRef = new File("thisismyfile.psd");
With no luck! Any ideas?
Failing that, is it possible to code it so that it says:
"If this is mac, then search for the file here. If this is windows, then search for the file here."?
I ended up using this script to determine the location of the file depending on whether the system being used is mac or windows.
function isMacOS() {
return ($.os.toLowerCase().indexOf('mac') >= 0);
}
var fileRef = isMacOS()
? new File("/Library/Application Support/Adobe/CEP/extensions/my.panel/files/filename.psd")
: new File("C:\Program Files\Common Files\Adobe\CEP\extensions\my.panel\files\filename.psd");
var docRef = app.open(fileRef);
};

List Google Drive files from a given folder on a webpage

I'm looking for a way to list all files in specific google drive folder, also which updates the list automatically, and let everyone possible to look. I've found quite amount of articles that creates a spreadsheet to list them but they don't update themselves. I just can understand bit of JavaScript of I tried to modify some of other codes to no avail. Here is what I've done.
I created a Google Apps Script file
function doGet(e){
return HtmlService.createHtmlOutputFromFile('list.html');}
and inside list.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var dir = "SpinFest2016 KPDS Clips"
function listFilesInFolder(dir) {
var folder = DriveApp.getFoldersByName(dir).next();
var contents = folder.getFiles();
var file;
var name = [];
var date = [];
var desc = [];
for (var i = 0; i < contents.length; i++) {
file = contents[i];
name[i] = file.getName();
date[i] = file.getDateCreated();
desc[i] = file.getDescription();
};
};
</script>
</head>
<table style ="width: 100%">
<tr>
<th>이름</th>
<th>제출일</th>
<th>비고</th>
<tr>
<td><p id="name"></p></td>
<td><p id="date"></p></td>
<td><p id="desc"></p></td>
</tr>
<script type="text/javascript">
document.getElementById("name").innerHTML = name;
</script>
</table>
</body>
</html>
I tried to list only file names first but it never worked, and I can't figure out what's wrong. If you can point me which part is wrong and what I have to do, I'd very appreciate you're help. If there's any other better way (not only google-apps-script but also other ways to display file list) that fits conditions below I'd very thankful.
lists file names in google drive
anyone with link can view the list
list updates automatically (whether periodically or on any change occurs)
getFiles() will return a FileIterator, it may not have a .length property. Change the loop into a while-loop and check if the iterator hasNext is true, this way it will iterate. Also, try to change how you push items in to the array. See the modified snippet, hopefully this works.
while (contents.hasNext()){
file = contents.next();
name.push(file.getName());
date.push(file.getDateCreated());
desc.push(file.getDescription());
};
What goes after this, how you display it will be up to you.
As written, your doGet gives a web browser an HTML page with some JS code embedded in it, which the browser will try to execute. And fail, since a web browser has no idea about DriveApp; it can run JavaScript, not Apps Script.
It's possible to execute Apps Script code in scriplets embedded in a page served by doGet, but the syntax make take a while to get used to.
For a simple page like yours, I would just create all HTML within doGet function, and serve that. See my example.
There was one more issue with your code: folder.getFiles() returns a file iterator, not an array. This is something you loop over using hasNext and next methods, as shown below.
function doGet(e) {
var template = '<table style ="width: 100%"><tr><th>name</th><th>Date</th><th>Description</th></tr>APPS_SCRIPT_CONTENT</table>';
var dir = 'SpinFest2016 KPDS Clips';
var folder = DriveApp.getFoldersByName(dir).next();
var contents = folder.getFiles();
var file, name, date, desc, list = [];
while (contents.hasNext()) {
file = contents.next();
name = file.getName();
date = file.getDateCreated();
desc = file.getDescription();
list.push('<tr><td>' + name + '</td><td>' + date + '</td><td>' + desc + '</td></tr>');
}
var output = HtmlService.createHtmlOutput(template.replace('APPS_SCRIPT_CONTENT', list.join('')));
return output.setTitle('Directory List').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
This will serve up a static HTML file with the current snapshot of the directory. If the user reloads, they will get a possibly fresher copy. The file will not update on its own if the directory contents are changed; I don't think this even possible on this platform. With a scriplet running Apps Script code, one could try to update periodically, but this seems hardly practical: why waste your Apps Script execution time quota on users who opened your webpage and went for a walk?

Is there a way to automatically detect the excel version from a html file or active x?

I have a workflow process that runs in weird combination of html and excel, this was already done when I came to work here so I'm no able to restart the process, well here is the deal:
After a certain step on the flow, a html file is sent through email, this file contains an active x that will automatically open excel with some given parameters, however even though everything seems to build with parameters the path for excel is hardcoded, we never had an issue with this as everyone was using Excel 2003 and pretty much everyone had the same image so the path was the same, but now some users (top management) will be migrating to office 2010. Therefore I need a way to automatically detect the excel version through the active x so the html file will open the correct excel version.
Any ideas?
Thanks!
EDIT
this is what I use:
<script language="JavaScript">
function LoadVendor()
{
var vendor = document.getElementById("vendor").value;
document.getElementById("vend").innerHTML=vendor;
var BIDnum = document.getElementById("BIDnumber").value;
document.getElementById("BIDnum").innerHTML=BIDnum;
}
function openExcelDocPath()
{
var shell = new ActiveXObject("WScript.Shell");
var excelexe = document.getElementById("excelexe").value;
var excelprg = document.getElementById("excelprg").value;
var vendor = document.getElementById("vendor").value;
document.getElementById("vend").innerHTML=vendor;
shell.run( "\"" + excelexe + "\"" + excelprg , 1, false );
try{objExcel.comaddins("SAS.OIBootStrap.Connect").connect = "False"; }
catch(err)
{ }
}
</script>
I'm not 100% on what your after but you could drop the physical path entirely;
var Excel = new ActiveXObject("excel.application");
Excel.Visible = true;
Excel.Workbooks.Add(); //to keep resident if you want interactivity
//can open something here ...
//or just get the path/version
alert( Excel.version );
alert( Excel.path );
//to kill
//Excel.Quit();
//Excel = null;

WIX: Where and how should my CustomAction create and read a temporary file?

I have a script CustomAction (Yes, I know all about the opinions that say don't use script CustomActions. I have a different opinion.)
I'd like to run a command, and capture the output. I can do this using the WScript.Shell COM object, then invoking shell.Exec(). But, this flashes a visible console window for the executed command.
To avoid that, I understand I can use the shell.Run() call, and specify "hidden" for the window appearance. But .Run() doesn't give me access to the StdOut of the executed process, so that means I'd need to create a temporary file and redirect the exe output to the temp file, then later read that temp file in script.
Some questions:
is this gonna work?
How do I generate a name for the temporary file? In .NET I could use a static method in the System.IO namespace, but I am using script here. I need to insure that the use has RW access, and also that no anti-virus program is going to puke on this.
Better ideas? I am trying very hard to avoid C/C++.
I could avoid all this if there were a way to query websites in IIS7 from script, without resorting to the IIS6 Compatibility pack, without using .NET (Microsoft.Web.Administration.ServerManager), and without execing a process (appcmd list sites).
I already asked a separate question on that topic; any suggestions on that would also be appreciated.
Answering my own question...
yes, this is going to work.
Use the Scripting.FileSystemObject thing within Javascript. There's a GetTempName() method that produces a file name suitable for temporary use, and a GetSpecialFolder() method that gets the location of the temp folder. There's even a BuildPath() method to combine them.
so far I don't have any better ideas.
Here's the code I used:
function GetWebSites_IIS7_B()
{
var ParseOneLine = function(oneLine) {
...regex parsing of output...
};
LogMessage("GetWebSites_IIS7_B() ENTER");
var shell = new ActiveXObject("WScript.Shell");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var tmpdir = fso.GetSpecialFolder(SpecialFolders.TemporaryFolder);
var tmpFileName = fso.BuildPath(tmpdir, fso.GetTempName());
var windir = fso.GetSpecialFolder(SpecialFolders.WindowsFolder);
var appcmd = fso.BuildPath(windir,"system32\\inetsrv\\appcmd.exe") + " list sites";
// use cmd.exe to redirect the output
var rc = shell.Run("%comspec% /c " + appcmd + "> " + tmpFileName, WindowStyle.Hidden, true);
// WindowStyle.Hidden == 0
var ts = fso.OpenTextFile(tmpFileName, OpenMode.ForReading);
var sites = [];
// Read from the file and parse the results.
while (!ts.AtEndOfStream) {
var oneLine = ts.ReadLine();
var line = ParseOneLine(oneLine);
LogMessage(" site: " + line.name);
sites.push(line);
}
ts.Close();
fso.DeleteFile(tmpFileName);
return sites;
}

How to resolve the C:\fakepath?

<input type="file" id="file-id" name="file_name" onchange="theimage();">
This is my upload button.
<input type="text" name="file_path" id="file-path">
This is the text field where I have to show the full path of the file.
function theimage(){
var filename = document.getElementById('file-id').value;
document.getElementById('file-path').value = filename;
alert(filename);
}
This is the JavaScript which solve my problem. But in the alert value gives me
C:\fakepath\test.csv
and Mozilla gives me:
test.csv
But I want the local fully qualified file path. How to resolve this issue?
If this is due to browser security issue then what should be the alternate way to do this?
Some browsers have a security feature that prevents JavaScript from knowing your file's local full path. It makes sense - as a client, you don't want the server to know your local machine's filesystem. It would be nice if all browsers did this.
Use
document.getElementById("file-id").files[0].name;
instead of
document.getElementById('file-id').value
I use the object FileReader on the input onchange event for your input file type! This example uses the readAsDataURL function and for that reason you should have an tag. The FileReader object also has readAsBinaryString to get the binary data, which can later be used to create the same file on your server
Example:
var input = document.getElementById("inputFile");
var fReader = new FileReader();
fReader.readAsDataURL(input.files[0]);
fReader.onloadend = function(event){
var img = document.getElementById("yourImgTag");
img.src = event.target.result;
}
If you go to Internet Explorer, Tools, Internet Option, Security, Custom, find the "Include local directory path When uploading files to a server" (it is quite a ways down) and click on "Enable" . This will work
I am happy that browsers care to save us from intrusive scripts and the like. I am not happy with IE putting something into the browser that makes a simple style-fix look like a hack-attack!
I've used a < span > to represent the file-input so that I could apply appropriate styling to the < div > instead of the < input > (once again, because of IE). Now due to this IE want's to show the User a path with a value that's just guaranteed to put them on guard and in the very least apprehensive (if not totally scare them off?!)... MORE IE-CRAP!
Anyhow, thanks to to those who posted the explanation here: IE Browser Security: Appending "fakepath" to file path in input[type="file"], I've put together a minor fixer-upper...
The code below does two things - it fixes a lte IE8 bug where the onChange event doesn't fire until the upload field's onBlur and it updates an element with a cleaned filepath that won't scare the User.
// self-calling lambda to for jQuery shorthand "$" namespace
(function($){
// document onReady wrapper
$().ready(function(){
// check for the nefarious IE
if($.browser.msie) {
// capture the file input fields
var fileInput = $('input[type="file"]');
// add presentational <span> tags "underneath" all file input fields for styling
fileInput.after(
$(document.createElement('span')).addClass('file-underlay')
);
// bind onClick to get the file-path and update the style <div>
fileInput.click(function(){
// need to capture $(this) because setTimeout() is on the
// Window keyword 'this' changes context in it
var fileContext = $(this);
// capture the timer as well as set setTimeout()
// we use setTimeout() because IE pauses timers when a file dialog opens
// in this manner we give ourselves a "pseudo-onChange" handler
var ieBugTimeout = setTimeout(function(){
// set vars
var filePath = fileContext.val(),
fileUnderlay = fileContext.siblings('.file-underlay');
// check for IE's lovely security speil
if(filePath.match(/fakepath/)) {
// update the file-path text using case-insensitive regex
filePath = filePath.replace(/C:\\fakepath\\/i, '');
}
// update the text in the file-underlay <span>
fileUnderlay.text(filePath);
// clear the timer var
clearTimeout(ieBugTimeout);
}, 10);
});
}
});
})(jQuery);
On Chrome/Chromium based apps like electron you can just use the target.files:
(I'm using React JS on this example)
const onChange = (event) => {
const value = event.target.value;
// this will return C:\fakepath\somefile.ext
console.log(value);
const files = event.target.files;
//this will return an ARRAY of File object
console.log(files);
}
return (
<input type="file" onChange={onChange} />
)
The File object I'm talking above looks like this:
{
fullName: "C:\Users\myname\Downloads\somefile.ext"
lastModified: 1593086858659
lastModifiedDate: (the date)
name: "somefile.ext"
size: 10235546
type: ""
webkitRelativePath: ""
}
So then you can just get the fullName if you wanna get the path.
Note that this would only work on chrome/chromium browsers, so if you don't have to support other browsers (like if you're building an electron project) you can use this.
I came accross the same problem. In IE8 it could be worked-around by creating a hidden input after the file input control. The fill this with the value of it's previous sibling. In IE9 this has been fixed aswell.
My reason in wanting to get to know the full path was to create an javascript image preview before uploading. Now I have to upload the file to create a preview of the selected image.
If you really need to send the full path of the uploded file, then you'd probably have to use something like a signed java applet as there isn't any way to get this information if the browser doesn't send it.
Use file readers:
$(document).ready(function() {
$("#input-file").change(function() {
var length = this.files.length;
if (!length) {
return false;
}
useImage(this);
});
});
// Creating the function
function useImage(img) {
var file = img.files[0];
var imagefile = file.type;
var match = ["image/jpeg", "image/png", "image/jpg"];
if (!((imagefile == match[0]) || (imagefile == match[1]) || (imagefile == match[2]))) {
alert("Invalid File Extension");
} else {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(img.files[0]);
}
function imageIsLoaded(e) {
$('div.withBckImage').css({ 'background-image': "url(" + e.target.result + ")" });
}
}
seems you can't find the full path in you localhost by js, but you can hide the fakepath to just show the file name. Use jQuery to get the file input's selected filename without the path
The best solution for this, I've found, is to use a middleware like Multer. Here's a quick rundown:
npm i multer
Add enctype="multipart/form-data" to your html form.
In your backend dock where you're making your post request, require multer (const multer = require('multer'))
In the same dock, set your upload destination: const upload = multer({dest:'uploas/'}). This will automatically create a local folder called 'uploads' where your files will be added. The code I've included shows you how to upload to your local disk storage. If you're using cloud storage (e.g. AWS, Azure, Cloudinary etc.) you can check out the Multer docs to see how to manage that. There aren't too many extra steps though.
in your post request, add 'upload.single' (for one file) or 'upload.array' (for multiple files), like this:
router.post('/new', upload.single('image'), async function(req, res) { //'image' should be the name of the input you're sending in the req.body
console.log(req.file) //note, if you're using 'upload.array', this should be 'req.files'
});
the req.file will have a full path name that you can use in your post request. For more information, check out the Multer docs:
https://www.npmjs.com/package/multer
I hope this helps!
You would be able to get at least temporary created copy of the file path on your machine. The only condition here is your input element should be within a form
What you have to do else is putting in the form an attribute enctype, e.g.:
<form id="formid" enctype="multipart/form-data" method="post" action="{{url('/add_a_note' )}}">...</form>
you can find the path string at the bottom.
It opens stream to file and then deletes it.
Hy there , in my case i am using asp.net development environment, so i was want to upload those data in asynchronus ajax request , in [webMethod] you can not catch the file uploader since it is not static element ,
so i had to make a turnover for such solution by fixing the path , than convert the wanted image into bytes to save it in DB .
Here is my javascript function ,
hope it helps you:
function FixPath(Path)
{
var HiddenPath = Path.toString();
alert(HiddenPath.indexOf("FakePath"));
if (HiddenPath.indexOf("FakePath") > 1)
{
var UnwantedLength = HiddenPath.indexOf("FakePath") + 7;
MainStringLength = HiddenPath.length - UnwantedLength;
var thisArray =[];
var i = 0;
var FinalString= "";
while (i < MainStringLength)
{
thisArray[i] = HiddenPath[UnwantedLength + i + 1];
i++;
}
var j = 0;
while (j < MainStringLength-1)
{
if (thisArray[j] != ",")
{
FinalString += thisArray[j];
}
j++;
}
FinalString = "~" + FinalString;
alert(FinalString);
return FinalString;
}
else
{
return HiddenPath;
}
}
here only for testing :
$(document).ready(function () {
FixPath("hakounaMatata:/7ekmaTa3mahaLaziz/FakePath/EnsaLmadiLiYghiz");
});
// this will give you : ~/EnsaLmadiLiYghiz

Categories

Resources