I have an ASP.NET MVC Application where I can choose a .log File. This happens with a FileReader. But when the explorer opens, all kind of datas are displayed (.png, .jpg, .docx....). So I want, that only the .log Files are displayed.
Here is my code:
// Input File (BUTTON)
const input = document.querySelector('input[type="file"]');
//Get data input from user
input.addEventListener('change', function (e) {
$('#fileName').html(input.files[0].name);
const reader = new FileReader()
reader.onload = function () {
const reslt = reader.result;
readFile(reslt);
}
reader.readAsText(input.files[0])
document.getElementById('rankings').style.display = 'none';
}, false)
This question relates more to html than to javascript. You should use the accept attribute and list a comma separated extensions accepted.
In your case:
<input type="file" accept=".log" />
Try this code.
//Get data input from user
input.addEventListener('change', function (e) {
let kind = $('#fileName').html(input.files[0].name);
if(kind != undefined && kind.indexOf('.log') > 0) {
const reader = new FileReader()
reader.onload = function () {
const reslt = reader.result;
readFile(reslt);
}
reader.readAsText(input.files[0])
document.getElementById('rankings').style.display = 'none';
}
}, false)
Hop is save you day.
Related
I am pretty new to javascript. Im trying to upload my image file but somehow I can only browse my file and my image is not uploading. I had a problem with inputField.addEventListener('change', function(e){});
I can see that my addEventListener('click', () => {}) is working fine but I dont understand if I did inputField.click(); it did not get into the inputField.addEventListener('change', function(e){});
const draggerArea = document.getElementById('dragger');
const inputField = document.getElementById('fileInputField');
const dragText = document.getElementById('drag-text');
const fileName = document.getElementById('fileName');
const browseFile = document.getElementById('uploadFile');
browseFile.addEventListener('click', () => {
inputField.value = ""
alert(String("hello"))
inputField.click();
});
inputField.addEventListener('change', function(e) {
file = this.files[0];
alert(String(file))
fileHandler(file);
});
const fileHandler = (file) => {
alert("hello")
const validExt = ["image/jpeg", "image/jpg", "image/png"]
if (validExt.includes(file.type)) {
const fileReader = new FileReader();
fileReader.onload = () => {
const fileURL = fileReader.result;
let imgTag = `<img src=${fileURL} alt=""/>`
draggerArea.innerHTML = imgTag;
let paragraph = `<div class="fileName"><p>${file.name.split('.')[0]}</p><i class="fa-solid fa-trash-can" onclick={deleteHandler()}></i></div>`
fileName.innerHTML = paragraph;
}
fileReader.readAsDataURL(file);
draggerArea.classList.add('active')
} else {
draggerArea.classList.remove('active');
dragText.textContent = "Drag and Drop File"
}
};
<div id="dragger_wrapper">
<div id="dragger">
<div class="icon"><i class="fa-solid fa-images"></i></div>
<h2 id="drag-text">Drag and Drop File</h2>
<h3>Or</h3>
<button class="uploadFile" id="uploadFile">Browse File</button>
<input type="file" hidden id="fileInputField" />
</div>
<div id="fileName"> </div>
</div>
<script src="dragAndDropController.js"></script>
modified code
you have no problem with inputField.addEventListener('change', function(e){});
tutorial on youtube
You want to to click hidden input and it is also working when you click browse button. This is not complete upload process . It is just displaying the file and need to store image in server.
Here is uploading with php
I'm developing a website to recommend clothes. So, I want customers to put their image which is in their local.
First, I tried <input type='file' accept='image/*' ~~>. But it doesn't provide customizing option. I must show the button with my picture.
Therefore I tried button option and write the code like this.
function openImageFile() {
var input = document.createElement("input");
input.type = "file";
input.accept = "image/*";
input.click();
input.onchange = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function() {
var dataurl = reader.result;
var output = document.getElementById('output');
output.src = dataURL;
output.width = 125;
output.height = 125;
};
photo = input.files[0];
reader.readAsDataURL(input.files[0]);
}
}
<button type="button" id="test" onclick="openImageFile()"><img src="blah.png"></button>
<img id='output'>`
Convert your image to data protocol.
Converter: https://base64.guru/converter/encode/image
Set the src of your image element to:
<image src="data:image/png;base64,OUPUT_FROM_ENCODER" />
This allows your website to load a image without it being hosted by a URL
I'd like to create a dropdown menu and display all the files currently in a directory so when the user clicks on an item in that list of files, it prints to console the name of that file.
Here is what I've come up with so far:
HTML
<form method="post">
<select name="DropdownList">
<option value="file1">fileArray[0]</option>
<option value="file2">fileArray[1]</option>
<option value="file3">fileArray[2]</option>
<option value="file4">fileArray[3]</option>
</select>
</form>
The problem with doing this hardcoded is what if there are 10 files instead of 4? Trying to figure a more dynamic approach.
Javascript
document.getElementByName('DropdownList').addEventListener('click', function() {
window.update.forEach(function(d, 'data/baselinedata') {
var f = readStringFromFileAtPath(d);
console.log(f)
});
});
function readStringFromFileAtPath (pathOfFileToReadFrom) {
var request = new XMLHttpRequest();
request.open("GET", pathOfFileToReadFrom, false);
request.send(null);
var returnValue = request.responseText;
return returnValue;
}
I guess I just don't know how to make this to dynamic instead of hardcoding the names in the list. I'm kind of a noob to web programming
Edit:
Just for clarity, all I want to do is populate a dropdown list with the names of files in a directory. So when a user goes to click an item in that list, it will print or log (via console.log()) the contents of that file.
You can use <input type="file"> element with multiple attribute set, create two arrays containing File object and result of FileReader.readAsText() and File objects iterate FileList object at change event of input type="file" element to set .name at <option> element .textConten, .value to index of uploaded File append to <select> element, set .value of <textarea> element to selected option which corresponds to index of File as text within array
<input type="file" multiple><br>
<select></select><br>
<textarea></textarea>
<script>
const [input, select, textarea, reader] = [
document.querySelector("input[type=file]")
, document.querySelector("select")
, document.querySelector("textarea")
, new FileReader
];
let [files, data, fn] = [
[],
[], (file, reader) => new Promise((resolve, reject) => {
reader.onload = () => {
reader.onload = reader.onerror = null;
resolve(reader.result);
}
reader.onerror = reject;
reader.readAsText(file);
})
];
input.onchange = async() => {
select.innerHTML = "";
files.length = data.length = 0;
for (const file of input.files) {
const {
name
} = file;
const option = new Option(name, files.length);
files.push(file);
select.appendChild(option);
let result = await fn(file, reader);
data.push(result);
}
}
select.onchange = () => {
textarea.value = data[select.value];
}
</script>
I have a txt file which get read with javascript.
function handleTextFile(evt)
{
var files = evt.target.files;
var reader = new FileReader();
reader.onload = function(){
Text = reader.result.toLowerCase();
};
reader.readAsText(files[0]);
}
I want find in var >Text< all Dates.
The located date shall be saved in a variable. The only thing i know-> i can match date formats with code
var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
but i want not only a true or false output. I want the Value of this located date.
Anyone has a link or a some code for me?
Here is a working snipped with regex for dates in format 00-00-0000.
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) {
var myRegexp = /\b(\d{2}-\d{2}-\d{4})/g;
var match = myRegexp.exec(reader.result);
fileDisplayArea.innerText = match;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
<div id="page-wrapper">
<h1>Your date reader.</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
I used this tutorial to assemble snipped above .
We are working on a Email Encrypted Service. Here I have designed a html page (User Registration) where I have provided an area for uploading a file with extentions .crt, .cer and .der
This is HTML Content:
<section>
<label class="label">PubLic Key File</label>
<div>
<input type="file" id="fileInput">
</div>
<div id="fileDisplayArea"></div>
</section>
<button type="submit" class="button">Submit</button>
Javascript Code is:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerHTML = "";
var img = new Image();
img.src = reader.result;
fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!";
}
});
}
I have copied this Javascript Code (beginner in javascript) . It Only Accepts image file. I want to change this code which only accepts .crt, .cer and .der Extentions.
Thank you :)
Your current regex will actually match any filename that contains the word "image" (any part of the filename that is "image" followed by zero or more characters)
If you want to match filenames that end in ".crt", ".cer" or ".der", you can use this regex:
var imageType = /\.crt|cer|der$/
You can test regular expressions using Rubular