Trying to read a local file on page load in HTML - javascript

I'm creating a web application that references a local txt (or csv) file which will change every year. I want to be able to load the contents of the file into a <textarea> on page startup.
Right now, I have functional code for loading the contents into a <textarea> by using the <input> element (thanks to a previous StackOverflow question in 2015). The file is selected and an event listener will call a function once the input state gets changed. My challenge is modifying the code so that the file can be hard-coded and loaded on startup and still calling the function using an event (or changing the function to work without an event call).
index.html
<input type="file" id="fileinput" />
<script type="text/javascript" src="dataLoad.js"></script>
<script type="text/javascript">
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
<textarea rows=20 id="area"></textarea>
dataLoad.js
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var display = "";
//a lot of unimportant stuff here
document.getElementById('area').value = display;
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
This works fine, but I don't want to manually select the file to load, I want to hard-code the file. The "a lot of unimportant stuff here" parses the data in the file so I left it out for clarity sake.

You cannot due to security reasons.
You don't want the websites you visit to be able to do this, do you?
Try This:
<object width="300" height="300" type="text/plain" data="password.txt" border="0" >
</object

Assuming the <input type="file" /> has autocomplete on (which I believe it does by default), any files that were chosen/dragged onto the element should still be present on page load, so all you would need to do is manually trigger the change event that you added an eventListener for, like so:
<input type="file" id="fileinput" />
<textarea rows=20 id="area"></textarea>
<script>
var fileInput = document.getElementById('fileinput');
var event = new Event('change');
fileInput.addEventListener('change', readSingleFile, false);
fileInput.dispatchEvent(event);
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
alert("Processing file...");
}
}
</script>
This won't work in JSFiddle as it rebuilds the HTML when you refresh the page, however this works offline for me.

Related

Alasql import from upload button vs file onchange event

I am trying to figure out how to import a file into ALASQL from a file input. There is documentation on how to do this but my client wants to have to press a load button vs when choosing the file.
Here is the documentation from ALASQL:
<script src="xlsx.core.min.js"></script>
<p>Select CSV file to read:</p>
<input id="readfile" type="file" onchange="loadFile(event)"/>
<script>
function loadFile(event) {
alasql('SELECT * FROM FILE(?,{headers:true})',[event],function(data){
// Process data here
});
}
</script>
https://github.com/agershun/alasql/wiki/How%20to%20upload%20form%20for%20txt%20and%20xlsx%20in%20javascript
My client wants something like this:
<script src="xlsx.core.min.js"></script>
<p>Select CSV file to read:</p>
<input id="readfile" type="file"/>
<button onclick="loadfile()">Load</button>
<script>
function loadFile() {
var file=document.getElementById('readfile').files[0]
alasql('SELECT * FROM FILE(?,{headers:true})',[file],function(data){
// Process data here
});
}
</script>
I have tried various methods to achieve this but nothing has worked so far. Some of the methods I have tried include creating custom jQuery events and the above example.
I have found a SF article that asks something similar but was unanswered.
Loading CSV file with AlaSQL and JQuery
Thank you
One answer I came up with is to split the loadfile process into two functions such as this:
<script src="xlsx.core.min.js"></script>
<p>Select CSV file to read:</p>
<input id="readfile" type="file" onchange="loadfile(event)"/>
<button onclick="loadfile2()">Load</button>
<script>
var loadFileTempData=[];
function loadFile() { //load data file into variable
var file=document.getElementById('readfile').files[0]
alasql('SELECT * FROM FILE(?,{headers:true})',[file],function(data){
loadFileTempData=data;
});
}
function loadFile2(){ //process data from variable
var data=loadFileTempData;
loadFileTempData=[];
// Process data here
}
</script>

Ajax file upload: what happens by default in form.onsubmit()?

I have a Java servlet that receives a file, processes it and then writes the resulting file back through HttpServletResponse's OutputStream.
For upload, I use a simple form:
<form id="upload-form" action="MyServlet" method="POST" enctype="multipart/form-data">
Select file to convert:
<input type="file" id="file-select" name="myfile" />
<button type="submit" id="upload-button">Upload</button>
</form>
After the file has been processed, a download dialog opens automatically.
Since processing may take a while (something like 30 seconds plus upload time), I wanted to provide some progress information through a websocket on the same page. This works if I do this:
var uploadForm = document.getElementById("upload-form");
var fileSelect = document.getElementById("file-select");
var uploadButton = document.getElementById("upload-button");
var httpRequest = new XMLHttpRequest();
uploadForm.onsubmit = function(event) {
event.preventDefault();
event.stopPropagation();
var file = fileSelect.files[0];
var formData = new FormData();
formData.append("myfile", file, file.name);
httpRequest.open("POST", "MyServlet", true);
httpRequest.send(formData);
};
The essential commands here seem to be event.preventDefault and event.stopPropagation.
The thing is: with this code, I get my progress info - but my download window never appears. If I comment out the two commands, it's the other way around. What happens by default when submitting a form, and (how) can I trigger that manually, so that I get both progress info AND the resulting file?
Note: I'm not using jQuery so far.

Upload file not working in Chrome extension option page

I am developing a chrome extension with an option page. On that page I put an upload image option but can't get the file to load in javascript. I have tried many solutions (1st solution, 2nd solution ...) but none worked. The strange thing is, that even an "onclick" attribute in the html code doesn't call the corresponding function. Here is an example of the code:
HTML example:
<input type="file" name="uploadImage" id="uploadImage" />
<button type="submit" id="imageUpload-btn" onclick="myFunction();">Upload</button>
javascript example:
jQuery("#imageUpload-btn").click(function(){
var image = new Image();
image.src = jQuery("#uploadImage").val();
alert(image.src);
image.onload = function(){
alert("on load");
}
image.onerror = function(){
alert("error");
}
});
I get the path of the file in the first alert, but then always the error alert. The function "myFunction()" is not called, but if I open the file directly in a browser the "onclick" trigger works and "myFunction()" is called.
What am I doing wrong or what am I missing?
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
<p>Filename: <INPUT type="file" name="submitfile" id = "submitfile" />
<INPUT type="button" value="Send" onClick="checkSize();" />
</form>
here you are using enctype="multipart/form-data" in this type we dont have opertunity to use
im.src = document.getElementById('submitfile').value;
you need to go for apache.commons.fileupload ServletFileUpload.isMultipartContent(request); which is totally java related.

How to display selected file name when using the Dropbox API JS Chooser

I am using the dropbox chooser (https://www.dropbox.com/developers/dropins/chooser/js) as part of a form. Once the user has selected a file, I would like to display that file name next to the chooser button.
It would also be nice to include a 'remove' link to clear the selection.
i assume that this will be done using javascript/jquery. Any help would be greatly appreciated.
EDIT: An earlier answer used e.files[0].link.split('/').pop(), but there's a field for this already! It's called name. Updated below.
The file name is one of the things returned, so you can just do this:
var url = e.files[0].link;
var name = e.files[0].name;
As to how to display it on the page, I would suggest adding a span somewhere and setting its text. Try this code, which does that and a couple other nice things (like handle the submit button's disabled state and resetting the Chooser button to its "unused" state):
<form>
<input id="chooser" type="dropbox-chooser" name="selected-file" data-link-type="direct" style="visibility: hidden;"/>
<p id="chosen" style="display:none">Chosen file: <span id="filename"></span> (<a id="remove" href="#">remove</a>)</p>
<input type="submit" id="submit" disabled />
</form>
<script>
$(function () {
$('#chooser').on('DbxChooserSuccess', function (e) {
var url = e.originalEvent.files[0].link;
var filename = e.originalEvent.files[0].name;
$('#chosen').show();
$('#filename').text(filename);
$('#submit').prop('disabled', false);
});
$('#remove').click(function (e) {
e.preventDefault();
$('#chosen').hide();
$('.dropbox-chooser').removeClass('dropbox-chooser-used');
$('#submit').prop('disabled', true);
});
});
</script>
EDIT
I should point out that the dropbox-chooser-used class is just something I noticed. Since it's not documented, that may change in a future version of the library. The rest should be fine.

Call function on file upload

I have a form which I'm using to upload files. In current situation if a user choose an image from his computer he have to click button upload to upload the image. I'm trying to find a way to skip the step with a button pressing.
How to call a javascript function when the file is selected from user ?
The onchange event is fired when a user specify a file for the upload filed. You could go about something like this:
<input type="file" name="someName" id="uploadID" />
Javascript:
var el = document.getElementById('#uploadID');
el.onchange = function(){
// your code...
};
However, javascript validation is good idea but make sure that you do the actual validation on the server-side :)
Using the example above...
<input type="file" name="someName" id="uploadID" />
JavaScript
document.getElementById('uploadID').addEventListener('change', () => {
//Your code...
});

Categories

Resources