I want to upload a csv file and process the data inside that file. What is the best method to do so? I prefer not to use php script. I did the following steps. But this method only returns the file name instead of file path.So i didnt get the desired output.
<form id='importPfForm'>
<input type='file' name='datafile' size='20'>
<input type='button' value='IMPORT' onclick='importPortfolioFunction()'/>
</form>
function importPortfolioFunction( arg ) {
var f = document.getElementById( 'importPfForm' );
var fileName= f.datafile.value;
}
So how can i get the data inside that file?
The example below is based on the html5rocks solution. It uses the browser's FileReader() function. Newer browsers only.
See http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files
In this example, the user selects an HTML file. It is displayed in the <textarea>.
<form enctype="multipart/form-data">
<input id="upload" type=file accept="text/html" name="files[]" size=30>
</form>
<textarea class="form-control" rows=35 cols=120 id="ms_word_filtered_html"></textarea>
<script>
function handleFileSelect(evt) {
let files = evt.target.files; // FileList object
// use the 1st file from the list
let f = files[0];
let reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
jQuery( '#ms_word_filtered_html' ).val( e.target.result );
};
})(f);
// Read in the image file as a data URL.
reader.readAsText(f);
}
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>
you can use the new HTML 5 file api to read file contents
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
but this won't work on every browser so you probably need a server side fallback.
The example below shows the basic usage of the FileReader to read the contents of an uploaded file. Here is a working Plunker of this example.
function init() {
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event) {
const reader = new FileReader()
reader.onload = handleFileLoad;
reader.readAsText(event.target.files[0])
}
function handleFileLoad(event) {
console.log(event);
document.getElementById('fileContent').textContent = event.target.result;
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body onload="init()">
<input id="fileInput" type="file" name="file" />
<pre id="fileContent"></pre>
</body>
</html>
There exist some new tools on the blob itself that you can use to read the files content as a promise that makes you not have to use the legacy FileReader
// What you need to listen for on the file input
function fileInputChange (evt) {
for (let file of evt.target.files) {
read(file)
}
}
async function read(file) {
// Read the file as text
console.log(await file.text())
// Read the file as ArrayBuffer to handle binary data
console.log(new Uint8Array(await file.arrayBuffer()))
// Abuse response to read json data
console.log(await new Response(file).json())
// Read large data chunk by chunk
console.log(file.stream())
}
read(new File(['{"data": "abc"}'], 'sample.json'))
Try This
document.getElementById('myfile').addEventListener('change', function() {
var GetFile = new FileReader();
GetFile .onload=function(){
// DO Somthing
document.getElementById('output').value= GetFile.result;
}
GetFile.readAsText(this.files[0]);
})
<input type="file" id="myfile">
<textarea id="output" rows="4" cols="50"></textarea>
FileReaderJS can read the files for you. You get the file content inside onLoad(e) event handler as e.target.result.
Related
I am trying to read the file using javascript new fileReader() function to convert the file in to binary format but is not supporting in Wix
please support us to resolve this issue to overcome it
var fr=new FileReader();
Hope This helps you :-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="file" />
<!-- writing JavaScript inside html -->
<body>
<input type="file" />
<!-- writing JavaScript inside html -->
<script>
const filename = document.querySelector('input[type="file"]');
filename.addEventListener('change', function (){
// Creating a FileReader object using the constructor.
const filereader = new FileReader();
// Reading a file as plain text
filereader.readAsText(filename.files[0]);
// Call this function to print the contents of the file
// once the file has been read.
filereader.onload = function {
console.log(filereader.result);
};
// Print the error incase there is one
filereader.onerror = function {
console.log("Error: ", filereader.error);
};
},false);
</script>
</body>
</body>
</html>
I think i have found a solution for you :-
try this
/* global FileReader */
$w.onReady(function () {
const fileReader = new FileReader();
fetch('https://static.wixstatic.com/media/e3b156_8646d72618e3420db36dba9156d0b8e7~mv2.jpg/v1/fit/w_512,h_586/o_0.jpeg')
.then(response => response.blob())
.then(blob => fileReader.readAsArrayBuffer(blob));
fileReader.onload = function () {
// your buffer array here. But why you need it? )))
console.log(fileReader.result);
}
})
Replace URL according to your needs.
Refer this Wix Corvid Api Overview
Can some one tell me why when all the File attributes are printed properly why FileReader.readAsArrayBuffer() is returning undefined in the following code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$( "#form" ).submit(function( event ) {
event.preventDefault();
var filevar=document.getElementById("file").files[0];
var reader=new FileReader() ;
console.log(filevar.name);
console.log(filevar.size);
console.log(filevar.type);
var file_contents= reader.readAsArrayBuffer(filevar);
console.log(file_contents);
});
});
</script>
<body>
<form action="" method="POST" id="form">
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname"><br>
Choose File : <input name="myFile" type="file" id="file">
<input type="submit" id="submit">
</form>
</body>
</html>
Reading a file is asynchronous. You have to wait until it's done.
var reader = new FileReader();
reader.onload = function(e){
let value = e.value; // alternatively reader.result
// do stuff with your value
};
reader.readAsArrayBuffer(filevar);
.readAsArrayBuffer does not return anything.
Alternatively, you can set up an async function for that so you don't have to use callbacks:
function readFile(file){
return new Promise((res, rej) => {
// create file reader
let reader = new FileReader();
// register event listeners
reader.addEventListener("loadend", e => res(e.target.result));
reader.addEventListener("error", rej);
// read file
reader.readAsArrayBuffer(file);
});
}
async function main(file){
// read file into typed array
let fileArrayBuffer = new Uint8Array(await readFile(file));
// do things with it
console.log(fileArrayBuffer);
}
// register event listener for input
document.querySelector("input[type=file]").addEventListener("change", e => {
let file = e.target.files[0];
main(file);
});
<input type="file">
FileReader is actually an async function. Some files are larger than others and so you do not want to lock the main thread.
If you want to see the result of the file. You should add a call back to the onload function of the reader.
var reader = new FileReader();
reader.onload = function(completionEvent) {
console.log(completionEvent);
// Set the result to whatever you need it as
}
reader.readAsArrayBuffer(filevar);
FileReader onload not getting fired on second time when the same file still selected with IE11 but the contents of file has changed, it's getting fired all the time for FireFox,Chrome.
Operation Details
On First Click, its all okay for all browsers(but IE sometime still missing some words from file).
After that I changed the contents of the file.
And then I click second attempt to btnDownload, Firefox and Chrome still reading the updated contents. BUT IE DOES NOT WORK!
.html
<input type="file" id="fileSelect" style="" accept=".csv">
<a type="button" class="btn" id="btnDownload" onclick="csvDownload()"
download> CSV DOWNLOAD </a>
myjavascript.js
var fileInput = document.getElementById("fileSelect"); //<input type="file" id="fileSelect">
var result = "";
readFile = function() {
changeAPInfoName();
if (!isFileSupported()) {
console.log('The browser does not support the API.');
} else {
if (fileInput.files.length > 0) {
var reader = new FileReader();
reader.onload = function() {
result = reader.result;
alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)");
document.getElementById('MY_HIDDEN_FIELD').setAttribute('value',result);
}
reader.readAsText(fileInput.files[0]);
reader.onerror = function() {
console.log('The file cannot be read.'+fileInput.files[0].fileName);
};
}
// EVENT FOR DOWNLOAD BUTTON!!!!
function csvDownload(){
readFile();
// using ajax to sent info from files and get download file.
}
Please help me with following issue.
How can I get to the line in reader.onload method although file contents are changed. alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)"); .
Replace this
reader.onload = function() {
result = reader.result;
alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)");
document.getElementById('MY_HIDDEN_FIELD').setAttribute('value',result);
}
with
reader.addEventListener("load",function(){
result = reader.result;
alert("WANT TO GET HERE ,ALTHOUGH FILE CONTENTS ARE CHANGED.(IN IE 11)");
document.getElementById('MY_HIDDEN_FIELD').setAttribute('value',result);
});
I hope this is helpful. I was facing the same problem and I used this method and it worked
Example of working FileReader:
<html>
<head>
<script>
function read(){
//Select the element containing file
var file =document.querySelector('input[type=file]').files[0];
//create a FileReader
reader = new FileReader();
//add a listener
reader.addEventListener('load',function(){
alert(reader.result);
},false);
if(file){
//ReadFile
reader.readAsDataURL(file);//You can read it in many other forms
}
}
</script>
</head>
<body>
<input type="file" name="myFile" id="myFile" onchange="read()">
</body>
</html>
For more on FileReader check this document out : Link
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
I've tried use javascript to open text file and get his name and his content, so right now I'm stuck at string, because I used input - type file to get directory / path.
Anyway, my question what is wrong in the next code, and how can i get text file content using javascript?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Display Text Files</title>
<script type="text/javascript">
var str = document.getElementById('txt').value;
function display() {
if (str != "") {
var filename = str.split("/").pop();
document.getElementById('filename').innerHTML = filename;
}
}
</script>
</head>
<body>
<form method="get" action="#" >
<input type="file" accept="text/plain" id="txt" />
<input type="submit" value="Display Text File" onclick="display();" />
</form>
</body>
</html>
EDIT: I also wanna disable in input file the all files opition (*) to text files only (.txt).
Thanks!
Modern browsers implementing FileReader can do this. To test your browser check if window.FileReader is defined.
Here is some code I wrote only this morning to do just this. In my case I simply drag a file onto the HTML element which is here referenced as panel.in1 but you can also use <input type="file" /> (see the reference below).
if (window.FileReader) {
function dragEvent (ev) {
ev.stopPropagation ();
ev.preventDefault ();
if (ev.type == 'drop') {
var reader = new FileReader ();
reader.onloadend = function (ev) { panel.in1.value += this.result; };
reader.readAsText (ev.dataTransfer.files[0]);
}
}
panel.in1.addEventListener ('dragenter', dragEvent, false);
panel.in1.addEventListener ('dragover', dragEvent, false);
panel.in1.addEventListener ('drop', dragEvent, false);
}
It is the reader.onloadend function which gets the text of the file which you recover in the event handler as this.result.
I got most of the mechanism on how to do this from MDN : https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications