Read file using javascript (file path is Known) - javascript

<!DOCTYPE html >
<html>
<head>
<title>Untitled Page</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
</head>
<body>
<input type="file" name="file" id="file">
<script type="text/javascript">
document.getElementById('file').onchange = function(){
// create a new instance of FileReader
var reader = new FileReader();
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < 3; line++){
document.write(lines[line]);
document.write("<br>");
}
};
reader.readAsText(file);
};
</script>
</body>
</html>
this is the code I used to read text file using given as a input. Without given as a input I want to read file which already know path.(eg: "index.html") .How could I want to change this code..

Related

Loading images uploaded with a form not showing

The user uploads images with a form. The images should all be displayed in the canvas. Only one of multiple images shows. Maybe the images are not properly loaded?
html:
let value = 0;
var images = [];
function setup() {
createCanvas(320, 270);
background(0);
const form = document.querySelector('form');
frameRate(2);
form.addEventListener('submit', e => {
e.preventDefault();
var preview = document.querySelector('img'); //selects the query named img
var files = form.querySelector('[type=file]').files;
if (files[0]) {
for(let i = 0; i < files.length; i++){
var reader = new FileReader();
reader.onloadend = function () {
//preview.src = reader.result;
images[i] = loadImage(reader.result);
console.log('new image added')
console.log(images[i]);
}
reader.readAsDataURL(files[i]); //reads the data as a URL
}
}
});
}
let cursor = 0;
function draw() {
background(0);
if(images.length > 0){ image(images[cursor], 0, 0, width, height - 20); }
cursor ++;
if(cursor >= images.length){ cursor = 0}
fill(255);
textSize(16);
text(value, 10, height - 10);
console.log(cursor);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>image_classification</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/addons/p5.dom.min.js"></script>
<script src="https://unpkg.com/ml5#0.1.1/dist/ml5.min.js"></script>
<script src="sketch.js"></script>
</head>
<body>
<h1>Welcome to the site!</h1>
<form id="imgs" method="post" enctype="multipart/form-data">
images:
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload File" name="submit">
</form>
<br/>
</body>
</html>
I have no idea where the problem even lays. Is it me inserting the images into the array incorrectly, or am I doing something wrong with the asynchronous nature of JavaScript?
Thanks in advance.
Your problem is caused by JavaScript scoping.
Take a look at this part of your code:
for(let i = 0; i < files.length; i++){
var reader = new FileReader();
reader.onloadend = function () {
images[i] = loadImage(reader.result);
}
reader.readAsDataURL(files[i]);
}
Because you're using the var keyword, your reader is actually in function scope. From MDN:
The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value.
This is why your reader variable only appears to work for one of your images.
The simplest fix to this is to use const instead of var here:
const reader = new FileReader();
The const keyword creates variables in block scope which is probably what you expected var to do in the first place.

preview the uploaded .pdf file in ASP web form

I am building an ASP webform application. I used
<asp:FileUpload runat="server" ID="fubillPhoto" onchange="showPreviewBill(this);" />
...to upload a pdf file. I want users to be able to review the uploaded file before submitting the form.
My idea is to create an element. When the user clicks on it a new tab open with PDF file. unfortunately I could not apply my idea... Here is my code:
HTML
<asp:FileUpload runat="server" ID="fuBillPhoto" onchange="showPreviewBill(this);" />
<div runat="server" id="divPdfBill" class="hidden">
<a runat="server" id="pdfBilllink" href="#" target="_blank">click here</a>
</div>
=====
Javascript
function showPreviewBill(input) {
var pdfLink = document.getElementById('#<%=pdfBilllink.ClientID %>');
var file = document.querySelector('#<%=fubillPhoto.ClientID %>').files[0];
var reader = new FileReader();
reader.onloadend = function () {
if (reader.result) {
$('#<%=pdfBilllink.ClientIDMode %>').attr("href", reader.result);
$('#<%=divPdfBill.ClientID %>').attr("class", "");
}
}
$('#<%=pdfBilllink.ClientIDMode %>').attr("href", reader.result);
It does not work! Please advise.
Load data uri from input file control use javascript file api.
Convert data uri to binary.
Show binary data in canvas using PDF.js.
here is a reference on how to do that with code
[link] https://forums.asp.net/t/2062665.aspx?Preview+pdf+file+before+upload
code from above reference website
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../Scripts/jquery-1.10.2.js"></script>
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#pdfInp").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
showInCanvas(e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
function convertDataURIToBinary(dataURI) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
function showInCanvas(url) {
// See README for overview
'use strict';
// Fetch the PDF document from the URL using promises
var pdfAsArray = convertDataURIToBinary(url);
PDFJS.getDocument(pdfAsArray).then(function (pdf) {
// Using promise to fetch the page
pdf.getPage(1).then(function (page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
// Prepare canvas using PDF page dimensions
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
});
}
});
</script>
</head>
<body>
<form id="form1" >
<p>
<input type='file' id="pdfInp" />
<canvas id="the-canvas" style="border:1px solid black"></canvas>
</p>
</form>
</body>
</html>
<asp:FileUpload runat="server" ID="fubillPhoto" onchange="showPreviewBill(this);"
/>`enter code here`

JavaScript - Reading file with HTML5 FileReader

I'm currently learning JavaScript and I'm struggling to read a txt file and use its contents in the program, what I have so far:
fileBtn.addEventListener("change", function()
{
var content = [];
var file = fileBtn.files[0];
readFile(file, function(data)
{
console.log(JSON.parse(data));
//content.push(JSON.parse(data)) doesn't work, data is undef.
});
});
and a function readFile
function readFile(file, f)
{
var reader = new FileReader();
reader.onload = function(evt)
{
f(evt.target.result);
};
reader.readAsText(file);
}
My txt file is currenty only containing a "1", and it logs this number to the console but I can't work with it, if I try to push it into an array the values is suddenly undefined. My goal is to use the content of the file in the program later on
1 . no need to use JSON.parse if the text file only contain string .
data is containing all the text file content
2 . you need to put var content = [];
globally and not inside the function readFile
follow this snippet of code i think it will solve your problem
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<label for="file-upload" class="custom-file-upload">
Custom Upload
</label>
<input id="file-upload" type="file" />
<input id="log-content" type="button" value="Click Me"/>
</body>
<script>
var content = [];
function readFile(file, f) {
var reader = new FileReader();
reader.onload = function (evt) {
f(evt.target.result);
};
var text = reader.readAsText(file);
}
var fileBtn = document.getElementById("file-upload");
var logContnt = document.getElementById("log-content");
logContnt.addEventListener("click", function () {
alert(content);
})
fileBtn.addEventListener("change", function () {
var file = fileBtn.files[0];
readFile(file, function (data) {
content.push(data);
});
});
</script>
</html>

To display text from a txt file using javascript

How to read text from a txt file with one button to browse the file and other button to display text. Pls help me in getting the code. i have tried many codes but othing worked. some code was like this. Thanks in advance
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "#":
output=output.split("\n").filter(/./.test, /\#/).join("\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}//end if html5 filelist support
}
</script>
</head>
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
</html>
You should properly read an article like this: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Dont think this line is working properly:
output=output.split("\n").filter(/./.test, /\#/).join("\n");
Try changing it to:
output=output.split("\n").filter(function(l) {
//return /^\#/.test(l); // Starting with #
return l.indexOf('#') > -1; // Containing #
}).join("\n");
It would be interesting to see if this would work as well:
output=output.split("\n").filter(/\#/.test.bind(/\#/)).join("\n");
The second arguments passed to the .filter method is the context:
array.filter(callback[, thisObject])
Get the input file, use FileReader() to read it,on file load get text that matches the pattern. Finally display it through "main" div. Should work..
HTML :
<input id="fileInput" type="file"/>
<div id="main"></div>
jQuery :
$(function(){
$("#fileInput").change(function(e){
var myFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function(e){
var output = e.target.result;
output=output.split("\n").filter(/./.test, /\#/).join("\n");
$("#main").text(output);
};
reader.readAsText(myFile)
});
}
)
Demo

Preview Image without Upload to my server

Hello how i can preview Image without upload to my server in asp.net C# and when i see the image i should press upload to upload to server.
In a HTML5 capable browser you can use the FileReader object to read a file from the users hdd as a base64 encoded string.
You can use this base64 representation with css to show the preview.
In older browsers you will need flash or similar plugin-based code to do it.
Here is a HTML5 example that works in all modern browsers:
<html>
<head>
<script>
var elmFileUpload = document.getElementById('file-upload');
function onFileUploadChange(e) {
var file = e.target.files[0];
var fr = new FileReader();
fr.onload = onFileReaderLoad;
fr.readAsDataURL(file);
}
function onFileReaderLoad(e) {
var bgStyle = "url('" +e.target.result + "')";
elmFileUpload.parentElement.style.background = bgStyle;
};
elmFileUpload.addEventListener('change',onFileUploadChange,false);
</script>
</head>
<body>
<input type="file" id="file-upload"/>
</body>
</html>
See a fiddle of it in action here
Yes it is possible.
Html
<input type="file" accept="image/*" onchange="showMyImage(this)" />
<br/>
<img id="thumbnil" style="width:20%; margin-top:10px;" src="" alt="image"/>
JS
function showMyImage(fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img=document.getElementById("thumbnil");
img.file = file;
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
}
You can get Live Demo from here.

Categories