How to read and display html file - javascript

I'm making a html editor but the problem is that when someone needs to view an html file i don't know how to display the text from the file.
<input type="file" onchange="previewFile()"><br>
<p id="txt1" src="blank.html"></p>
<script>
function previewFile() {
const preview = document.getElementById('txt1');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
// reads image file to a blob string
preview.src = window.URL.createObjectURL(file);
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
</script>
I used this script to read a file and display it by changing the paragraph src to a blob link, but looks like the paragraph dosn't get the text by a html text link using src.
Is there a way to do it?

The paragraph does not have src attribute, You need to use either innerText or innerHTML to display the content.
function previewFile() {
const content = document.querySelector('.content');
const [file] = document.querySelector('input[type=file]').files;
const reader = new FileReader();
reader.addEventListener("load", () => {
// this will then display a text file
content.innerText = reader.result;
}, false);
if (file) {
reader.readAsText(file);
}
}
<input type="file" onchange="previewFile()"><br>
<p class="content"></p>

The p tag does not support src attribute so the alternative solutions would be using element.innerHTML= text or you change the p tag into iframe

Related

How do I create an <img> tag that javascript can modify?

I want to write a simple html page where there is an img tag and an input tag.
I am trying to write the javascript that will read the users image file selection and change or add the 'src' in the img tag to show the users image without uploading it to a server.
This isn't working and I cannot figure it out:
<input type="file" id="file">
<img id="user_img" src="user_img">
<script type="text\javascript" >
const user_img = document.querySelector('#img')
document.querySelector('#file').addEventListener('input', event => {
if (event.target.files.length === 0) {
console.error('No file provided')
return
}
const reader = new FileReader()
reader.addEventListener('loadend', () => {
user_img.src = reader.result
})
reader.readAsDataURL(event.target.files[0])
})
</script>

Unable to display multiple uploaded images in HTML

I'm trying to upload multiple images onto my webpage but I'm having trouble understanding how to get a valid URL for the source of the image and to check if the number of files uploaded is correct. How should I go about doing so? Here is a sample of the code I have written:
<div id = "image_display">
<input type="file" id="image" name="image" multiple>
</div>
const img = document.getElementById('image');
const display = document.getElementById('image_display');
img.onchange = evt =>{
const [file] = img.files;
if(file){
const newImg = document.createElement('img',{
src : URL.createObjectURL(file)
})
display.appendChild(newImg)
}
}
You need to break-up the creation of the image.
use document.createElement to create the image
set the new image's src
const newImg = document.createElement('img');
newImg.src = URL.createObjectURL( file );

Read a .txt file and output him in <p> HTML (with JS)

I have tried a lot of possibilities, but most of them don't work or require modules, but I don't know how to do this in vanilla javascript.. I really need some help.. Thanks. (Sorry for my bad English, I'm french)
My script : (don't really work, just read)
<script type="text/javascript">
var fso, ts, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.OpenTextFile("pub.txt", 1);
s = ts.ReadLine();
</script>
Reading a text file:
fetch('file.txt')
.then(response => response.text())
.then(text => console.log(text))
// outputs the content of the text file
Using Jquery:
$("#div7").load("ajax.txt");
Try this out!
<input type="file" onchange="readFile(this)" />
<script>
function readFile(input) {
let file = input.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function () {
document.getElementById("app").innerHTML = `<p>${reader.result}</p>`;
};
reader.onerror = function () {
console.log(reader.error);
};
}
</script>
document.querySelector("input[type='file']").addEventListener("change", function(){
if(this.files[0]){
this.files[0].text()
.then(val => {
document.querySelector("p").textContent = val;
})
}
})
<label>Pick One Text File</label><br/>
<input type="file" accept="text/plain" multiple="false"> <br/>
<label>File Will Show up here in the text box</label><br/><br/>
<p></p>
Edit: a working example here
https://codepen.io/engeslamadell/pen/WNrVPeG
did you tried this
<script type="text/javascript">
//this is the input with type file
document.getElementById('inputfile')
.addEventListener('change', function() {
var fr=new FileReader();
fr.onload=function(){
document.getElementById('output')
.textContent=fr.result;
}
fr.readAsText(this.files[0]);
})
</script>
you also have these FileReader methods
FileReader.readAsArrayBuffer(): Reads the contents of the specified input file. The result attribute contains an ArrayBuffer representing the file’s data.
FileReader.readAsBinaryString(): Reads the contents of the specified input file. The result attribute contains the raw binary data from the file as a string.
FileReader.readAsDataURL(): Reads the contents of the specified input file. The result attribute contains a URL representing the file’s data.
FileReader.readAsText(): Reads the contents of the specified input file. The result attribute contains the contents of the file as a text string. This method can take encoding version as the second argument(if required). The default encoding is UTF-8.
source: https://www.geeksforgeeks.org/how-to-read-a-local-text-file-using-javascript/

Image cannot be read when pasted

I made a tool which converts images to base64 data.
<input id="inp" type='file'><br>
<br>
<textarea readonly placeholder="Base64 data" id="b64"></textarea>
<br>
<img id="img">
<script>
function readFile() {
if (this.files && this.files[0]) {
var FR= new FileReader();
FR.addEventListener("load", function(e) {
document.getElementById("img").src = e.target.result;
document.getElementById("b64").innerHTML = e.target.result;
});
FR.readAsDataURL( this.files[0] );
}
}
window.addEventListener('paste', e => {
document.getElementById("inp").files = e.clipboardData.files;
});
document.getElementById("inp").addEventListener("change", readFile);
</script>
Image can be uploaded either by using <input id="inp" type='file'>, or by directly copying and pasting the image from clipboard onto the window.
Here is the problem; when image is uploaded through the usual <input>, it renders the base64 data within seconds, however when pasting the image from clipboard onto the window, the input seems to recognize the image as image.png but no data gets rendered. How can I solve this problem?

Display image thumbnail of image selected from filepicker

I'm using a regular HTML File Picker input form item to allow my users to select files. I'd like to show them a thumbnail of the file they selected as they will be required to select many images and it can get confusing.
Does anyone know if it's possible to display the image they selected without uploading it to the server? If so, how?
If someone can point me to a post or give me an idea of how I might do this it will be greatly appreciated.
<input type="file" name="image" accept="image/*">
<!-- Create an <img> element to preview the image -->
<img id="image-preview" width="320">
<!-- The <input> can go anywhere in your page or <form>. Note the "onchange" attribute -->
<input type="file" name="image" accept="image/*" onchange="handleFileChange">
Make sure the following JavaScript comes after the above <img> and <input> elements. You can put this in your .js file that is loaded at the end of the page or in a <script> element at the end of page.
// Select the preview image element
const imgElement = document.getElementById('image-preview');
function handleFileChange(e) {
// If no file was selected, empty the preview <img>
if(!e.target.files.length) return imgElement.src = '';
// Set the <img>'s src to a reference URL to the selected file
return imgElement.src = URL.createObjectURL(e.target.files.item(0))
}
This should get you started
http://jsfiddle.net/41go76g4/
Basically you read the file in with fileAPI in javascript and set the returned blob as the dataURL for an img tag.
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('fileInput').addEventListener('change', handleFileSelect, false);
ref: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Categories

Resources