Javascript get local file path via a dialog - javascript

I'm writing a database application in node.js via electron. The user needs to be able to select a json file from anywhere on their system, and I need to get the path or in some other way copy it to the program directory. I've tried a variety of different methods but the only thing that even makes a dialog is <input type="file">, but that returns a path with fakepath in it (I believe this is for browser security, but I don't need that since again, electron app). Any help is appreciated

You can use the dialog.showOpenDialog api.
dialog.showOpenDialog([browserWindow, ]options[, callback])
browserWindow BrowserWindow (optional)
options Object
title String
defaultPath String
filters Array
properties Array - Contains which features the dialog should use, can contain openFile, openDirectory, multiSelections and createDirectory
callback Function (optional)
Example
const dialog = require('electron').dialog;
console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', 'multiSelections' ]}));

Related

Search through files in path using only javascript

I'm coding a webpage that needs to read some data from different csv on a path depending on the country of the user.
the path is something like this:
./csv/m2-2022-10-25_13_45_55_es.csv
m2-2022-10-25_13_45_56_fr.csv
m2-2022-10-25_13_46_04_it.csv
etc
And those files will be replaced regularly, the only that we'll always have is the country code (es, fr, it, etc).
So, what I need is to list all the files on the path to an array, and loop through the array to find if the last characters of the filename are $countryCode + ".csv", and there run some code.
But I can't find how, all the solutions I find are using Node.js, but are there a solution using only Javascript (or jQuery)?
Regards!
You cannot use pure Javascript to do that, because if you wanted to search files in your computer only using javascript, it would be a huge security breach.
You must use node.js to open files but you can make an API to your nodejs file from your javascript and you can send as a response the content of your file.
Here some links that might help you :
FS : https://nodejs.org/api/fs.html
NodeJS api : https://medium.com/swlh/how-to-create-a-simple-restful-api-in-node-js-ae4bfddea158
You can check a similar question here:
Get list of filenames in folder with Javascript
You can't access to filesystem from the frontend, this it would be a huge security breach, because anyone could access to your filesystem tree.
You have to do a function in backend to build the array you want and send it to frontend.
If you create a function in backend file that returns the array of files in the folder, you can call it from the frontend via XMLHttpRequest or Fetch to get the array in frontend and be able to use in your js file.

How to set location for input file via Javascript?

I have the next input on a webpage
<input accept="image/jpeg" class="class1" type="file">
And I'm trying to set it's file location via chrome console , I've tried to do the next thing
var Files = ['C:/Users/user/Desktop/dir/toUpload/file.jpg'];
var upload=document.getElementsByClassName("class1");
upload.files = Files;
But it seems to have no effect on the page at all.
How can I achieve to upload a file that way? (There is no submit button just file input)
I'm 90% sure that this isn't possible from JavaScript. The browser creates a File object after a user gesture. Allowing the page to create files without user gestures would enable random pages to read local files on user's computers.
File objects are generally retrieved from a FileList object returned as a result of a user selecting files using the element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement. In Gecko, privileged code can create File objects representing any local file without user interaction (see Implementation notes for more information.)
https://developer.mozilla.org/en-US/docs/Web/API/File

Keeping information about js file in localStorage

I want to create plugin mechanizm. It is, you can load js file on my website and run your js "plugin" (function) when this plugin is set to run (toggled as running).
All this I want to do without any server.
I mean, I want to keep in localstorage js files or path to this files.
It looks to be hard to do because js can't easy access files path.
I handle file by <input type="file"/>
And I react on onchange event. I get event where I can find selected file by event.srcElement.files[0]
With that I can create URL of that object by : URL.createObjectURL(event.srcElement.files[0])
And I tried to store that URL in localstorage but this URL is temporary.
Also I tried to store whole event or just file (event.srcElement.files[0]).
But I need to create string from that if I want to put it to the function .setItem :
localStorage.setItem("functionURL", JSON.stringify(this.functionURL));
.toString() creates [Object Event/File]
JSON.stringify() creates {} from [Object Event/File]
So, maybe is there a way to somehow remember file which we can use as a function without any server ?
So, maybe is there a way to somehow remember file which we can use as a function without any server ?
Basically, no. :-) Web storage only stores strings. You can't use a string to access a file on the user's local filesystem from your web page, for obvious security reasons.
You could, instead:
Make it possible for them to "upload" the file into your page (without a server) by having them identify the file in an input[type=file], reading its text (via the File API), and then storing that text in local storage
On page load, if local storage has code to run, run it
Offer the user a way to delete or update the code they've uploaded to the page
Since all of that happens in the browser, you don't need a server.
Web storage does have size limits, though they're pretty generous, (around 2.5-5MB) and per-origin, so you have that largely to yourself. But if you run into those limits, you could take it further by caching those files via a service worker, but the complexity goes up markedly. I'd start with web storage and only move on if you really need to support massive files.
#1 (reading the script file the user identifies via an input[type=file]) is really simple on modern browsers:
var file = input.files[0];
var fr = new FileReader();
fr.onload = function() {
// Use `fr.result` here, it's a string containing the text
};
fr.readAsText(file);

How to write a text file in Acrobat Javascript

I am using acrobat XI
I have tried output a text file like this
var cMyC = "abc";
var doc = this.createDataObject({cName: "test.txt", cValue: cMyC});
this.exportDataObject({cName: "test.txt", nLaunch:0});
This is working , but I would like to provided a fixed path and no dialog is popup to request the user choose a saving path
Are there any way to fix the problem? thanks
All Acrobat JavaScript functions that write a file to the user’s local disk pose a security risk, so there are some restrictions placed on their use. These functions include doc.saveAs() and all of the data export functions, like doc.exportAsFDF().
As you can read here:
Acrobat provides us with two modes of operation for these
functions--with a path and without a path. If no path parameter is
provided to the function, Acrobat displays a file-browser dialog. The
file browser dialog gives users control over how data is saved to
their systems. If a path is provided to the function, then no dialog
is displayed and the operation is handled silently, i.e., the user is
not necessarily aware that data has been saved to their hard drive.
This is a security problem, so to use one of these functions in silent
mode, the function must be executed from a privileged context. This
means the code must reside in a trusted location. For example, code
executed from the Console Window, a Batch Process or a certified PDF
is privileged. When any of these functions are used with a path
parameter and executed in a non-privileged context, Acrobat will throw
an exception. The reasoning behind this restriction is, if the code
can’t be trusted, then the user has to specifically select the file
location.
Another restriction on saving data to the user’s system is that the
path specification must be a Safe Path. A safe path is one that
doesn’t point to a restricted location on the user’s hard drive or one
that might pose a security risk. Examples of these restricted
locations are the system folder and the root folder of any hard drive.
Other folders that might be restricted are dependent on the operating
system and the sensibilities of the Acrobat developers. Neither is
well documented, so it’s best to use these functions carefully.
About "Safe Paths", the Acrobat JS API doc.saveAS method documentation states:
Acrobat 6.0 introduced the concept of a safe path for JavaScript
methods that write data to the local hard drive based on a path passed
to it by one of its parameters. A path cannot point to a system
critical folder, for example a root, windows or system directory. A
path is also subject to other unspecified tests. For many methods, the
file name must have an extension appropriate to the type of data that
is to be saved. Some methods may have a no-overwrite restriction.
These additional restrictions are noted in the documentation.
Generally, when a path is judged to be not safe, a NotAllowedError
exception is thrown (see Error object) and the method fails.
For sure you can't do it with the exportDataObject method, since it has no path parameter, as you can also read here:
The "cName" parameter is a required input and specifies the specific
file attachment that will be exported. Notice there is no path
parameter. There is in fact a "cPath" input to this function, but it
is no longer valid. If you try to use a path in this function, it will
fail and throw an exception. It doesn't matter what context the
function is called from because the "cPath" parameter was removed from
all usage.
Further references:
Write Text file using Acrobat Javascript
Acrobat Javascript Save and Exit Button
Here's a way to output to a fixed path text file using doc.exportAsText:
// set up output text
var TEMP_FIELD_NAME = "testHeader"
var textValue = "test";
// add a temporary text field
var f = this.addField(TEMP_FIELD_NAME, "text", 0, [30,30,100,20]);
f.value = textValue;
// export field name and value to defined file
this.exportAsText({aFields: TEMP_FIELD_NAME, cPath: "test-text.txt"});
// remove text field
this.removeField(TEMP_FIELD_NAME);
The resulting text file will have two lines:
testHeader
test
Impossible. For security reasons, saving a file automatically is not allowed.
As stated in the SDK:
Beginning with Acrobat 6.0, if the parameter cDIPath is non-null, a NotAllowedError exception is thrown and the method fails.
If cDIPath is not passed to this method, a file selection dialog box opens to allow the user to select a save path for the embedded data object.

How to distinguish a file from a folder while uploading using drag and drop in jquery?

If a user tries to drag and drop a folder to my file uploader control for uploading it, then I need to show an error message to the user saying that only files can be uploaded. The problem is I couldn't distinguish a file from a folder.
One way I thought was to check for file type property of jQuery. Supposing that the name of the file is "test.txt", then file type would return "text/plain". For a normal folder name such as "TestFolder", file type would be blank and its file size would return 0. However if the folder name included an extension like "TestFolder.txt", then file type would return "text/plain".
So I could have checked for file type and file size but it would not work correctly for folder name like "TestFolder.txt". Could any one suggest me a good solution to fix this using jQuery or other methods?
The ability to determine if a folder has been dropped is dependent on the user agent's support of the Filesystem API. If the user agent DOES support the Filesystem API (currently only Chrome 21+), you can make use of the Entry interface, which has two child interfaces: DirectoryEntry and FileEntry. The interface itself has isDirectory and isFile functions. Without support for this interface, there is no way to determine if dropped items are folders when examining the DataTransfer object.
Since you are not going to allow folder to drag and drop, first check if it's folder or file, second only if it's not folder then check for file extension. But IE < 11 does not support file API to handle. Hope it helps.
As far as I'm aware the browser (And javascript inherently) doesn't have access to any file access methodologies for security purposes so you cannot check what the file actually is.
I have worked with this problem myself in the past and the best option I have found that works is to handle the file server-side, and return the error back to the page after upload has completed.
I would be happy to see better alternatives myself though.

Categories

Resources