I have some javascript which loads a file based on user input:
function openFile(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function () {
const result = reader.result.split("base64,")[1];
// use result
};
reader.readAsDataURL(input.files[0]);
}
I want to hard-code the file name. If I were writing to file, I would try something like
function openFile2(filename) {
var reader = new FileReader();
reader.onload = function () {
const result = reader.result.split("base64,")[1];
// use result
};
var file = new File([""], filename) // create a new file object for writing (not actually desired)
reader.readAsDataURL(file);
}
But here I am reading, so I want an existing file, not a new one. I've found several similar questions in which the answers assert that this is not possible for security reasons:
- How to read local files using HTML 5 FileReader?
- How to read file in Java Script line by line from hardcoded path and name of the file?
- How to set a value to a file input in HTML?
- Javascript read file without using input
I have, however, seen some references to a Chrome option --allow-file-access-from-files
which seems to be intended to override this security feature. My javascript is intended for local use only, so it would be totally acceptable for it to only work only in Chrome and only with this option. My problem is I don't know enough about javascript to know how to create a file object for reading, and I can't seem to find documentation on how one would (just assertions that it's forbidden).
My questions:
- Is loading a file based on a hard-coded name 'forbidden' in the sense that one can write the javascript, but a browser won't run it as instructed, or is it 'forbidden' in the sense that the command does not exist in javascript?
- Given that my project is intended for local use only, and I am therefore able to select any browser/launch flag combination required (e.g. Chrome with
--allow-file-access-from-files
), what is the easiest way to get a javascript file object (suitable forfilereader
) from a hard-coded path? For example, if it can't be done in pure javascript, can I put something in my html which hooks in to the javascript?