I have a file reader that works on jfiddle but wont work in any browser. Im using all the latest browsers,. It will let me select the file, but nothing happens afterwards. Im very new to javascript.
javacript
<script type="text/javascript">
function readFile(file) {
var reader = new FileReader();
reader.onload = readSuccess;
function readSuccess(evt) {
var field = document.getElementById('main');
field.innerHTML = evt.target.result;
};
reader.readAsText(file);
}
document.getElementById('selectedFile').onchange = function(e) {
readFile(e.srcElement.files[0]);
};
</script>
html
<input type="file" id="selectedFile" />
<div id="main"></div>
jfiddle
http://jsfiddle.net/fstreamz/ngXBV/1/
Use window.onload or window.addEventListener("load")
<script type="text/javascript">
window.onload = function() {
function readFile(file) {
var reader = new FileReader();
reader.onload = readSuccess;
function readSuccess(evt) {
var field = document.getElementById("main");
field.innerHTML = evt.target.result;
};
reader.readAsText(file);
}
document.getElementById("selectedFile").onchange = function(e) {
readFile(e.srcElement.files[0]);
};
}
</script>
Here is the html
<input type="file" id="selectedFile" accept="text/plain" />
<div id="main"></div>
Related
This question already has answers here:
Javascript read file without using input
(3 answers)
Closed 9 months ago.
I'm trying to load simple text file in javascript, unfortunately with no success.
my code is:
var my_text:any;
var my_file:File = new File([], "C:\\Users\\riki7\\Downloads\\classes.txt");
var reader = new FileReader();
reader.onload = function() {
my_text = reader.result;
};
reader.readAsText(my_file);
alert(my_text);
after this code runs, I would expect to see classes.txt file content in pop-up alert, instead I get 'undefined'.
my file contains a, b, c.
does anyone know what is my problem? maybe the first parameter for File() constructor?
You have to use html tag <input type="file" id="input" /> and then hung a event listener on it, like that
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
const fileList = this.files; /* now you can work with the file list */
}
then after simply bypass your file into the FileReader
const reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
And i guess that would be it.
You can find more examples there: https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications
Having your code where your alert runs upfront the callback function. If you need to see alter with the content, simply move your alert into the callback function:
reader.onload = function() {
my_text = reader.result;
alert(my_text);
};
because my_text is not ready when you call alert outside.
<input type="file" id="selectedFile">
<p id="display"></p>
<script>
var fr = new FileReader();
let test;
document.getElementById('selectedFile').addEventListener('change', x);
function x() {
fr.onload = ()=>{
document.getElementById('display').innerText = fr.result;
test = fr.result;
alert(fr.result);
}
fr.readAsText(this.files[0]);
}
</script>
<html>
<head>
<script>
var fileReadEvent = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var text = reader.result;
alert(text)
};
};
</script>
</head>
<body>
<input type='file' accept='text/plain' onchange='fileReadEvent(event)'><br>
</body>
</html>
I have the following code:
function displayImg() {
let fileUpload = document.getElementById("fileUpload").value;
let container document.getElementById("container");
container.innerHTML = `<img src="fileUpload">`
}
<input type = file id = "fileUpload" accept = "image/*">
<button onclick = "displayImg()">Click to show</button>
<div id="container"></div>
I want it so that the user can input the file into the file Input field and it is placed into the source of a dynamically-created image upon button click. How do I do this?
You can try this
<html>
<body>
<input type = file id = "fileUpload" accept = "image/*">
<button onclick = "displayImg()">Click to show</button>
<div id="container">
<img id="img"></div>
<script>
function displayImg() {
let fileUpload = document.getElementById("fileUpload").value;
//alert(fileUpload);
let image = document.getElementById("img");
img.src = fileUpload;
}
</script>
</body>
</html>
NOTE: The value property only returns the name of the file so the image should be located in the same folder as that of code.Or if you want to, you can add the path of the file before.
please use the below code:
var uploadedFileURL;
function handleFile() {
var fileUploadControl = document.getElementById('fileUpload');
var file = fileUploadControl.files[0];
if (file) {
var reader = new FileReader();
reader.onload = function() {
uploadedFileURL = reader.result;
};
reader.readAsDataURL(file);
}
}
function displayImg() {
var fileUpload = document.getElementById("fileUpload").value;
var container = document.getElementById("container");
container.innerHTML = `<img src="${uploadedFileURL}">`;
}
<input id="fileUpload" type="file" onchange="handleFile()" accept="image/*" />
<button onclick="displayImg()">Click to show</button>
<div id="container"></div>
Here is a solution :
<input type="file" id="fileUpload" accept="image/*">
<button onclick="displayImg()">Click to show</button>
<div id="container">
<img id="img"></img>
</div>
<script>
let displayImg = () => {
let reader = new FileReader();
let input = document.getElementById('fileUpload');
reader.onload = () => {
let img = document.getElementById('img');
img.src = reader.result;
};
reader.readAsDataURL(input.files[0]);
};
</script>
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>
I am trying to get file contents with FileReader(), JavaScript.
I find this answer: https://stackoverflow.com/a/21962101/2898694
As #Markasoftware said in comments, I am trying to save result to var.
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var myFile = evt.target.files[0];
var reader = new FileReader();
var result;
reader.readAsText(myFile);
reader.onload=function(){
result = reader.result;
console.log(result); // works
}
console.log(result); // not works
}
If I am trying to see content in onload handler all fine, but out of it I can't see result. Why?
Because onload runs asynchrone. console.log(result); // not works is executed before the onload event has fired.
More on that: How do I return the response from an asynchronous call?
example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
var sizef = document.getElementById('uploadImage').files[0].size;
document.getElementById("uploadPreview").src = oFREvent.target.result;
document.getElementById("uploadImageValue").value = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var imgUrl = $('#uploadImageValue').val();
alert(imgUrl);
});
});
</script>
<div>
<input type="hidden" id="uploadImageValue" name="uploadImageValue" value="" />
<img id="uploadPreview" style="width: 150px; height: 150px;" /><br />
<input id="uploadImage" style="width:120px" type="file" size="10" accept="image/jpeg,image/gif, image/png" name="myPhoto" onchange="PreviewImage();" />
</div>
Source file
</body>
</html>
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.