Using the FileReader API - javascript

I am trying to read a local static file using the FileReader API but for some reason it's not reading anything. I am using:
var file = new File(
[""],
"config.toml"
);
var reader = new FileReader();
reader.onload = event => {
console.log(reader.result);
};
reader.readAsText(file);
The result is just empty. What am I doing wrong? Also, how will Javascript know where to look for config.toml?
EDIT: To clarify, I want to read the file from the server where the application is hosted not from the client machine.

In your code you are using File constructor which returns a newly constructed File, where the arguments are as follows:
var myFile = new File(bits, name[, options]);
bits An Array of ArrayBuffer, ArrayBufferView, Blob, or DOMString objects — or a mix of any such objects. This is the file content encoded as UTF-8
name A USVString representing the file name or the path to the file
It does read the file from the path you supply. So it will read the content you've passed to it, and you've passed to it an empty string.
If you want to read a file from file system you will need to use an input element with type attribute set to file and browse for it.
Here is an sample how to use the FileReader api to read images:
function handleFileSelect(evt) {
var files = evt.target.files;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = [
'<img class="thumb" src="',
e.target.result,
'" title="',
escape(theFile.name),
'"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

Related

How to get all url's image from a multiple input file?

I'm trying to get all url values from a multiple input file. It works correctly with just one image but if I try to attach more than one, I retrieve a null response and only get the last one correctly. I hope anybody could help with this issue!
Post my code below and JSFiddle example:
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
//show url image
var dataURL = reader.result;
alert(dataURL);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
https://jsfiddle.net/3q49moyj/

Error: Invalid or corrupted PDF file Firefox

I am trying to upload a PDF file and once done uploading, I am trying to show that PDF file in an IFrame with the stream content I have with me in scope. Same code works if I upload an image file but throws below error for PDF upload in Firefox.
Error
Invalid or corrupted PDF file.
PDF.js v1.9.583 (build: d7b37ae7)
Message: Invalid PDF structure
viewer.js:1359:7
Error: Invalid or corrupted PDF file.
HTML
<input type="file" id="files" name="files[]" multiple />
<iframe id="uploadedFileIframe" title="PDF in an i-Frame" src="" scrolling="auto" height="400" width="400" />
CSS
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
JavaScript
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('pdf.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var enc = btoa(unescape(encodeURIComponent( e.target.result)))
document.getElementById('uploadedFileIframe').setAttribute('src','data:application/pdf;base64,'+ enc);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
It looks like you've overengineered the solution a little bit
document.getElementById('uploadedFileIframe').src = reader.result;
should work if you place it instead of
var enc = btoa(unescape(encodeURIComponent( e.target.result)))
document.getElementById('uploadedFileIframe').setAttribute('src','data:application/pdf;base64,'+ enc);
https://jsfiddle.net/kc8sdas5/
You are accepting multiple files to be selected and you are always replacing the same iframe with a new source. You don't create a new iframe for each file. Also you don't have to read the file as a base64 string, it's pointless and also a bad for performances and memory. You could instead use the URL.createObjectURL instead, which is syncron, so you can get rid of your closure
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var previews = document.querySelector('#previews');
var iframe;
var URL = window.URL || webkitURL;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process pdf files.
if (!f.type.match('pdf.*')) {
continue;
}
iframe = document.createElement('iframe')
iframe.title = "PDF in an i-Frame";
iframe.scrolling = "auto";
iframe.width = iframe.hight = 400;
iframe.src = URL.createObjectURL(f);
previews.appendChild(iframe);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" name="files[]" multiple />
<div id="previews"></div>

Reading local file using JavaScript

So i have a file locally called "index.html" which i access using the "file://" protocol. (So not the "http://" protocol). I need to access a file "data.txt" in the same directory which is continuously changed by a seperate program, but since i'm using the file protocol the access to the file is denied for security reasons.
What could i do to read the local file? I thought of running a local server using XAMPP or WAMP but i'd rather not use any extra programs.
EDIT:
I cannot use an input file, since it should work without any user interaction.
You may do it via the File API - https://www.w3.org/TR/file-upload/
The example below filters out images from the user's selection, calls reader.readAsDataURL() on the file, and renders a thumbnail by setting the 'src' attribute to a data URL.
<style>
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
</style>
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

Javascript - Image Upload Preview - Remove the loop so it only submits a single file

I found this script online somewhere (I can't remember where) and it works well, for displaying the preview of an image before it's uploaded. The preview script is intended for multiple files but since I'm also saving data to a database, I need to restrict it to a single file. This script includes a loop that indexes the name of the file input and I'm having trouble targeting it with my php script that uploads the file and saves the data. So, I need to remove the loop so it works with only a single file, then I can give it a "regular" name and target it.
<input type="file" name="files[]" class="file" id="files">
<output id="list"></output>
<script type="text/javascript">
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
Thanks!
You should be able to give the input element any name you want and the code should still work.
see https://developer.mozilla.org/en-US/docs/Web/API/FileList for more information on the file property
The var files = evt.target.files; Should always an an array. If you really want to remove the loop, try this
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// instead of looping. go straight for the first array item
var f = files[0];
// Only process image files.
if (!f.type.match('image.*')) {
return;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);

Is it possible to read local files with javascript?

Having HTML document with Javascript code loaded from a local .html file (file:///C:/...) is there any way in pure Javascript (no jQuery) to read local .txt file with all major browsers without adding any flag, such as --allow-file-access-from-files in Chrome, etc.?
You can do this only with HTML5
Example from that site:
<style>
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
</style>
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

Categories

Resources