How to read a local file in JQuery or JavaScript? - javascript

I have an HTML file, which I want to read and append as HTML. I have tried the below codes but these codes are not working.
Approach 1:
var file = "abc.html";
var str = "";
var txtFile = new File(file);
txtFile.open("r");
while (!txtFile.eof) {
// read each line of text
str += txtFile.readln() + "\n";
}
$('#myapp').html(str);
Approach 2:
var file = "abc.html";
var rawFile = new XMLHttpRequest();
alert('33333333');
rawFile.open("GET", file, false);
alert('44444');
rawFile.onreadystatechange = function () {
alert('5555555555');
if (rawFile.readyState === 4) {
alert('66666666666');
alert(rawFile.readyState);
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
$('#myapp').html(allText);
alert(allText);
}
}
}
rawFile.send(null);
In Approach 2, it not going into the onreadystatechange method.
I thought another approach that I will use all the abc.html file content as a string variable and do similar $('#myapp').html(allText);, but this looks very bad approach because later I need to do the same for other 10-15 files. So Could you guys help me out?
Note: My application is running in offline mode means I cannot use the internet.
I have tried this solution, but its also not working.

It is not possible as JavaScript is frontend framework and it doesn't have access to local file system.
But you can do diffrent method.
-> you can serve that file in a local server and use http request with any backend framework.

I think you can adapt this pen to use as you wish:
https://codepen.io/alvaro-alves/pen/wxQwmg?editors=1111
CSS:
#drop_zone {
width: 100px;
height: 100px;
background: #000;
background-repeat: no-repeat;
background-size: 100px 100px;
opacity: 0.5;
border: 1px #000 dashed;
}
HTML:
<html>
<body>
<div id="drop_zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">
</div>
</body>
</html>
JS:
//drop handler do XML
function dropHandler(ev) {
ev.preventDefault();
var file, reader, parsed, emit, x, endereco;
if (ev.dataTransfer.items) {
for (var i = 0; i < ev.dataTransfer.items.length; i++) {
if (ev.dataTransfer.items[i].kind === 'file') {
file = ev.dataTransfer.items[i].getAsFile();
reader = new FileReader();
reader.onload = function() {
parsed = new DOMParser().parseFromString(this.result, "text/xml");
console.log(parsed);
};
reader.readAsText(file);
console.log('... file[' + i + '].name = ' + file.name);
}
}
}
removeDragData(ev)
}
function dragOverHandler(ev) {
ev.preventDefault();
}
function removeDragData(ev) {
if (ev.dataTransfer.items) {
ev.dataTransfer.items.clear();
} else {
ev.dataTransfer.clearData();
}
}
You will just to handle the result.

Related

How to dynamically create downloadable link from user uploaded files (disregarding file types) without calling server?

HTML:
<input id="browse" type="file" multiple>
<div id="preview"></div>
Javascript:
var elBrowse = document.getElementById("browse");
var elPreview = document.getElementById("preview");
function readFile(file) {
//Create downloadable link and generate DOM elements.
var fileName = file.name;
elPreview.insertAdjacentHTML("beforeend", "<a>" + fileName + '</a>');
elPreview.insertAdjacentHTML("beforeend", "<a>Delete</a><br>");
}
elBrowse.addEventListener("change", function () {
var files = this.files;
// Check for `files` (FileList) support and if contains at least one file:
if (files && files[0]) {
// Iterate over every File object in the FileList array
for (var i = 0; i < files.length; i++) {
var file = files[i];
readFile(file);
}
}
});
I am facing a new requirement, but I don't have much experience in Javascript. Basically, I want users to be able to upload files by clicking the browse button and displays the files name with downloadable link. User can upload files of any type and be able to download the files back.
The whole process MUST not trigger the backend server and everything has to be done in javascript or JQuery. Could anyone help please? Thank you.
System and User interaction:
User uploads a file
System saves the file in javascript and displays the file name with downloadable link.
User delete it.
System removes it from DOM and javascript
User can repeat step 1-4. The whole process does not trigger the server at all.
Eventually, user submits all the files to the server by clicking somewhere else (This step is out of the scope of this post)
If you are using a modern browser then you can utilize the HTML5 FileReader. I've used it, but found an example more suited to your question here.
You can use the FileReader to read the files on the client side, and store in sessionStorage, localStorage, or even a variable. But the one caveat is that you'll probably run out of RAM because JavaScript's not really designed for retaining large BLOBs in RAM.
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
html {
font-family: Helvetica, Arial, sans-serif;
font-size: 100%;
background: #333;
}
#page-wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
min-height: 300px;
border-top: 5px solid #69c773;
box-shadow: 0 2px 10px rgba(0,0,0,0.8);
}
h1 {
margin-top: 0;
}
img {
max-width: 100%;
}
#fileDisplayArea {
margin-top: 2em;
width: 100%;
overflow-x: auto;
}
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>

JavaScript - Change class when if/ elseif condition is fulfilled

I'm working on a script which reads a text file and changes the text in an div depending on the content of the .txt file.
But that isn't my Problem. I don't want just plain text, the background color should change depending on which condition of the if/elseif/else function is fulfilled.
var client = new XMLHttpRequest();
client.open('GET', 'text.txt');
client.onreadystatechange = function checktxt() {
if(client.responseText =='not')
{
document.getElementById("response").innerHTML="Connect is working";
var boxgreen = document.querySelector("#response");
boxgreen.classList.add("green");
}
else if (client.responseText =='younger')
{
document.getElementById("response").innerHTML="Connect is working";
var boxgreen = document.querySelector("#response");
boxgreen.classList.add("green");
}
else
{
document.getElementById("response").innerHTML="Connect isn't working!";
var boxred = document.querySelector("#response");
boxred.classList.add("red");
}
}
client.send();
.green {
width: 140px;
height: 140px;
background: #68B267;
color: white;
}
.red {
width: 140px;
height: 140px;
background: #ec4f3e;
color: white;
}
<div id="response"></div>
My first try was to add a "classList.add" to the if/ else function, but even if the "if" condition is fulfilled it changes the class to "red" because it has been set at last.
I'm pretty new to javascript and have no experience with ajax or jquery but maybe that's what I'm looking for.
If the code has run already, you need to remove the classes that you have added.
client.onreadystatechange = function checktxt() {
With your code, you can just call
boxgreen.classList.remove("red"); //or green for the other case
and than it will work.
Or you can use toggle and simplify the code so you do not have the same lines over and over again.
client.onreadystatechange = function() {
var isValid = client.responseText == 'not' || client.responseText == 'younger',
text = isValid ? "Connect is working" : "Connect isn't working!",
box = document.querySelector("#response");
box.innerHTML = text;
box.classList.toggle("green", isValid);
box.classList.toggle("red", !isValid);
}

Filereader - upload same file again not working

I have sth like drawing app. User can save projects and then load them. When I load first time one file (for e.g. project1.leds) make some changes in the app but no saving it and then again load same file (project1.leds) nothing happen. I cant load same file more than once. If I load another file, it's working.
Code:
$("#menu-open-file").change(function(e){
var data=[];
var file = null;
file = e.target.files[0];
console.log(file)
var reader = new FileReader();
reader.onload = function(e){
data=JSON.parse(reader.result);
x=data[0].SIZE[0];
y=data[0].SIZE[1];
if(x==15) x=16;
if(x==30) x=32;
if(x==60) x=64;
if(y==15) y=16;
if(y==30) y=32;
if(y==60) y=64;
createLeds(x,y,data,false,false);
clearActiveTools();
var svg = $('#contener').find('svg')[0];
svg.setAttribute('viewBox','0 0 ' + x*20 + ' ' + y*20);
$("#contener").css("width",x*20).css("height",y*20);
$("#contener").resizable({
aspectRatio: x/y,
minHeight: 200,
minWidth: 200,
});
wiFirst = $("#contener").width();
hiFirst = $("#contener").height();
}
reader.readAsText(file);
});
Can i delete/remove cached file? Is it even cached in browser?
It is because you're calling the function onchange. If you upload the same file the value of the file input has not changed from the previous upload and therefore isn't triggered. This also explains why it works if you upload a different file. No need to clear cache, you can work around this by resetting the input field's value after you read the file.
$("#menu-open-file").change(function(e){
var data=[];
var file = null;
file = e.target.files[0];
if(file !== ''){
console.log(file)
var reader = new FileReader();
reader.onload = function(e){
data=JSON.parse(reader.result);
x=data[0].SIZE[0];
y=data[0].SIZE[1];
if(x==15) x=16;
if(x==30) x=32;
if(x==60) x=64;
if(y==15) y=16;
if(y==30) y=32;
if(y==60) y=64;
createLeds(x,y,data,false,false);
clearActiveTools();
var svg = $('#contener').find('svg')[0];
svg.setAttribute('viewBox','0 0 ' + x*20 + ' ' + y*20);
$("#contener").css("width",x*20).css("height",y*20);
$("#contener").resizable({
aspectRatio: x/y,
minHeight: 200,
minWidth: 200,
});
wiFirst = $("#contener").width();
hiFirst = $("#contener").height();
}
reader.readAsText(file);
$("#menu-open-file")[0].value = '';
}
});
because input is caching the same file value so when you load the same file again it uses the cache to read value property. all you need to do is set a conditional statement when you use input element and set the value property of input to an empty string and it should work
input.value = "";
and if you are using an event handler then
e.target.value = "";
Try the below code, It should work. While clicking the upload button clear the existing value.
$("#menu-open-file").click(function(e){
$('#menu-open-file').val('');
}
The only problem with the above answer is that your HTML will no longer display the file name after the upload. Instead, it will continue to say "No file chosen", which might be confusing for users.
To get around this, you can hide the input and replace it with a label that replicates the display of the input, like so:
HTML:
<input type="file" id="myFileInput" />
<label id="myFileLabel" for="myFileInput">Choose file</label><span id="myFileName">No file chosen</span>
CSS:
#myFileInput {
display: none;
}
#myFileLabel {
border: 1px solid #ccc;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
margin-top: 5px;
padding-left: 6px;
padding-right: 6px;
}
#myFileName {
margin-left: 5px;
}
JavaScript:
var file = null
file = e.target.files[0];
//variable to get the name of the uploaded file
var fileName = file.name;
//replace "No file chosen" with the new file name
$('#myFileName').html(fileName);
well explained article how to do this here: https://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/
In Mozilla, everything was OK. But in Chrome, I faced the same problem:reader.onload was not uploading the same file a second time on the change event.
I was using pure javascript, and here is my solution!
HTML:
<input type="file" accept="image/*" name="image" id="file-input"/>
Javascript:
const fileInput = document.getElementById("file-input");
// My EventListener with change event and my_function
fileInput.addEventListener("change", my_function);
// reader.onload was used in my_function
//################### THIS IS THE SOLUTION ###################
// Add this EventListener to fix the problem with chrome
fileInput.addEventListener("click", function() {
fileInput.value = "";
});

How to show message if Adobe Reader is not installed?

I have embeded PDF on my page for which, using "<iFrame>" I am calling a HTML page which contains the <Object> tag with in that there is an <embed> tag which embeds the PDF and a tag which shows up if there is not Adobe Reader installed.
On Firefox, Chrome and IE 11 if the there is a PDF reader installed, it will show only the PDF but when there is no reader istalled it shows the message in <p> tag "install the Adobe reader".
My Issue is :- in IE10, even if the Adobe reader is installed it shows the message "install the Adobe reader" in <p> tag. Please suggest how to hide the message if Adobe Reader is installed and the message should show only if PDF Reader is not installed.
Here is my CODE:
Iframe code from where PDF page is being called:
<div id="pdf">
<iframe id="pdfIframe" name="pdfIframe" src="pdfView.html" style="width: 100%; height: 100%;" scrolling="auto" frameborder="1">
Your browser doesn't support inline frames.
</iframe>
</div>
PDF page Code:
<body>
<style>
html, body, #blankPane {
height: 100%;
margin: 0;
padding: 0;
}
#blankPane p {
font-weight: bold;
line-height: 30px;
height: auto;
width: 98%;
margin: 0 auto;
color: #bc0000;
}
#blankPane * {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
<div id="blankPane" class="overflowHidden">
<object data="lorem.pdf" type="application/pdf">
<p>
It appears you don't have Adobe Reader or PDF support in this web browser.
<br />
Click here to download the PDF OR Click here to install Adobe Reader
</p>
<embed id="pdfDocument" src="lorem.pdf" type="application/pdf" />
</object>
</div>
Please suggest!!!
You can detect which version of Adobe Acrobat that is installed with a javascript like the one below, or you can use FlexPaper to display your document if you prefer not to rely on Adobe Acrobat
var getAcrobatInfo = function() {
var getBrowserName = function() {
return this.name = this.name || function() {
var userAgent = navigator ? navigator.userAgent.toLowerCase() : "other";
if(userAgent.indexOf("chrome") > -1) return "chrome";
else if(userAgent.indexOf("safari") > -1) return "safari";
else if(userAgent.indexOf("msie") > -1) return "ie";
else if(userAgent.indexOf("firefox") > -1) return "firefox";
return userAgent;
}();
};
var getActiveXObject = function(name) {
try { return new ActiveXObject(name); } catch(e) {}
};
var getNavigatorPlugin = function(name) {
for(key in navigator.plugins) {
var plugin = navigator.plugins[key];
if(plugin.name == name) return plugin;
}
};
var getPDFPlugin = function() {
return this.plugin = this.plugin || function() {
if(getBrowserName() == 'ie') {
//
// load the activeX control
// AcroPDF.PDF is used by version 7 and later
// PDF.PdfCtrl is used by version 6 and earlier
return getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl');
}
else {
return getNavigatorPlugin('Adobe Acrobat') || getNavigatorPlugin('Chrome PDF Viewer') || getNavigatorPlugin('WebKit built-in PDF');
}
}();
};
var isAcrobatInstalled = function() {
return !!getPDFPlugin();
};
var getAcrobatVersion = function() {
try {
var plugin = getPDFPlugin();
if(getBrowserName() == 'ie') {
var versions = plugin.GetVersions().split(',');
var latest = versions[0].split('=');
return parseFloat(latest[1]);
}
if(plugin.version) return parseInt(plugin.version);
return plugin.name
}
catch(e) {
return null;
}
}
//
// The returned object
//
return {
browser: getBrowserName(),
acrobat: isAcrobatInstalled() ? 'installed' : false,
acrobatVersion: getAcrobatVersion()
};
};
Example of how to call these functions:
var info = getAcrobatInfo();
alert(info.browser+ " " + info.acrobat + " " + info.acrobatVersion);

Image upload on file chosen not on submit form , [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a HTML form where the user can upload an image in the input field and it works fine but the image is uploaded when the form is submitted.
Is there a way where I can get the image to upload to the TMP directory when the file is chosen and the user is still filling out the form then when the user submits the form it can be moved to the actual file directory. This would make for a better user experience and especially people with slow internet connections would benefit from this as it would utilise the users time for effectively and efficiently.
I am not sure exactly but I think this would need some sort of jQuery/Ajax solution to upload the image mid form entry then use PHP to transfer the file from the TMP to the actual directory.
As Diodeus suggested, putting the form in an iframe would prevent it from posting in the current page frame and allow users to work on other form items. A solution more to what you were expecting would be using an AJAX request. You could look into the HTML5 API, there are many different already-built solutions and many tutorials.
Here's a simple example taken from this demo at html5demos.com
<title>Drag and drop, automatic upload</title>
<style>
#holder { border: 10px dashed #ccc; width: 300px; min-height: 300px; margin: 20px auto;}
#holder.hover { border: 10px dashed #0c0; }
#holder img { display: block; margin: 10px auto; }
#holder p { margin: 10px; font-size: 14px; }
progress { width: 100%; }
progress:after { content: '%'; }
.fail { background: #c00; padding: 2px; color: #fff; }
.hidden { display: none !important;}
</style>
<article>
<div id="holder">
</div>
<p id="upload" class="hidden"><label>Drag & drop not supported, but you can still upload via this input field:<br><input type="file"></label></p>
<p id="filereader">File API & FileReader API not supported</p>
<p id="formdata">XHR2's FormData is not supported</p>
<p id="progress">XHR2's upload progress isn't supported</p>
<p>Upload progress: <progress id="uploadprogress" min="0" max="100" value="0">0</progress></p>
<p>Drag an image from your desktop on to the drop zone above to see the browser both render the preview, but also upload automatically to this server.</p>
</article>
<script>
var holder = document.getElementById('holder'),
tests = {
filereader: typeof FileReader != 'undefined',
dnd: 'draggable' in document.createElement('span'),
formdata: !!window.FormData,
progress: "upload" in new XMLHttpRequest
},
support = {
filereader: document.getElementById('filereader'),
formdata: document.getElementById('formdata'),
progress: document.getElementById('progress')
},
acceptedTypes = {
'image/png': true,
'image/jpeg': true,
'image/gif': true
},
progress = document.getElementById('uploadprogress'),
fileupload = document.getElementById('upload');
"filereader formdata progress".split(' ').forEach(function (api) {
if (tests[api] === false) {
support[api].className = 'fail';
} else {
// FFS. I could have done el.hidden = true, but IE doesn't support
// hidden, so I tried to create a polyfill that would extend the
// Element.prototype, but then IE10 doesn't even give me access
// to the Element object. Brilliant.
support[api].className = 'hidden';
}
});
function previewfile(file) {
if (tests.filereader === true && acceptedTypes[file.type] === true) {
var reader = new FileReader();
reader.onload = function (event) {
var image = new Image();
image.src = event.target.result;
image.width = 250; // a fake resize
holder.appendChild(image);
};
reader.readAsDataURL(file);
} else {
holder.innerHTML += '<p>Uploaded ' + file.name + ' ' + (file.size ? (file.size/1024|0) + 'K' : '');
console.log(file);
}
}
function readfiles(files) {
debugger;
var formData = tests.formdata ? new FormData() : null;
for (var i = 0; i < files.length; i++) {
if (tests.formdata) formData.append('file', files[i]);
previewfile(files[i]);
}
// now post a new XHR request
if (tests.formdata) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/devnull.php');
xhr.onload = function() {
progress.value = progress.innerHTML = 100;
};
if (tests.progress) {
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
var complete = (event.loaded / event.total * 100 | 0);
progress.value = progress.innerHTML = complete;
}
}
}
xhr.send(formData);
}
}
if (tests.dnd) {
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
this.className = '';
e.preventDefault();
readfiles(e.dataTransfer.files);
}
} else {
fileupload.className = 'hidden';
fileupload.querySelector('input').onchange = function () {
readfiles(this.files);
};
}
</script>
This creates a zone to drop a file (instead of a browse button) and initiate the file upload when the drag and drop event occurs. It will do it asynchronously and allow the page contents to be interacted with as normal while the transfer proceeds in the background. There is an important thing in this example to change, however. This line:
xhr.open('POST', '/devnull.php');
Should be changed to a code file in your environment/server that will process the file upload data and save or process the file however you need. This script merely acts as a front-end to that script. Another thing to remember is the HTML5 File API is still a modern-browser-only type of thing; it's well supported in current browsers, but older ones are out of luck. If you need to have them supported, you should look for another solution.

Categories