I am creating an image previw and upload page based on this https://demos.phplift.net/javascript-image-compress-using-html5-canvas-file-api/. It is working fine in all web browsers and in android firefox (version 88.1.4) it is not working with images have size greater than 1MB, no issues in android chrome browser. When I checked the image onload (in code it is i.onload()) function is not triggering for larger images in firefox
html
<form id="upload_form">
<label for="file">Choose file</label>
<input type="file" id="fileinput" />
</form>
javascript function is
<script>
var output_format = null;
var file_name = null;
function readFile(evt) {
var file = evt.target.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var i = document.getElementById("source_image");
console.log(i);
i.src = event.target.result;
i.onload = function(){
console.log("Image loaded");
}
};
output_format = file.name.split(".").pop();
file_name = file.name;
console.log("Filename:" + file.name);
console.log("Fileformat:" + output_format);
console.log("Filesize:" + (parseInt(file.size) / 1024) + " Kb");
console.log("Type:" + file.type);
reader.readAsDataURL(file);
return false;
}
document.getElementById("fileinput").addEventListener("change", readFile, false);
</script>
Does anyone know why images greater than 1 MB not trigring image onload in firefox?
Don't use the FileReader...
Think this can work:
i.src = URL.createObjectURL(file)
How can I loop this image convertion to base64 based on how many images are uploaded in file upload?
This script I am using, I want it to be looped based on how many images that are selected in the file upload:
<input id="inp" type='file' multiple>
<p id="b64"></p>
<img id="img" height="150">
<script>
document.getElementById("inp").addEventListener("change", readFile);
function readFile() {
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]);
}
</script>
Thank you!
<script>
var bs64Array = [];
document.getElementById("inp").addEventListener("change", readFile);
function readFile() {
var FR = new FileReader();
FR.addEventListener("load", function (e) {
var image = document.createElement('img')
image.src = e.target.result;
document.getElementById("b64").appendChild(image);
bs64Array.push(e.target.result)
});
FR.readAsDataURL(this.files[0]);
}
</script>
I allow the user to select a mp3 file from the local file System and then
allow to download the same file. Its for learning purpose.
<script type="text/javascript">
window.onload = function() {
document.querySelector('#musicFile').addEventListener('change', function(e){
var file = e.target.files[0];
console.log(e, file);
if(file.type.match('audio.*')) { // if its an audio file
var fReader = new FileReader();
fReader.onload = function(ev) { //onload event
var dataUrl = ev.target.result;
var downloadCon = document.querySelector('#download')
downloadCon.href = dataUrl;
};
fReader.readAsDataURL(file); //start reading the file
}
});
}
</script>
The HTML body:
<body>
<div class="controls">
<input type="file" id="musicFile">
<a id='download'href='#' download='music.mp3' class='downloadLink'>
Download File
</a>
</div>
</body>
When I click the Download File, nothing happens. Can you tell me what am I doing wrong?
You don't need to use FileReader to do that. Simply, you need to create a URLObject and make the A tag to point to it. The code for that (tested under Chrome and Firefox for Linux):
<script type="text/javascript">
window.onload = function() {
document.querySelector('#musicFile').addEventListener('change', function(e){
var file = e.target.files[0];
console.log(e, file);
if(file.type.match('audio.*')) { // if its an audio file
document.getElementById( 'download' ).href = URL.createObjectURL(file);
}
});
}
</script>
To be more specific at what I did in your code - I removed all the FileReader code and added
document.getElementById( 'download' ).href = URL.createObjectURL(file);
in it's place. I didn't touch your HTML.
Hope that helps.
I am trying to use the readAsDataURL function for a javascript FileReader in order to retrieve data from an html form to upload it into a database. I currently have a file Object from the form but cannot get it into a form to put into a database.
HTML
input type="file" style="width: 300px" id="costumePicUpload" multiple
button type="submit" onclick="submitForm()">SUBMIT</button
JavaScript
function submitForm(){
var file = document.getElementById("costumePicUpload").files[0];
var reader = new FileReader();
var img;
reader.onloadend = function(e) {
img = new Image();
img.src = e.target.result;
if(e.target.error){
alert(e.target.error.code);
}
};
reader.readAsDataURL(file);
};
}
When I output the link in an alert it just says undefined. Does anyone know how I can fix this?
UPDATE
I was able to get a FileError.NOT_READABLE_ERR but have no idea what could be causing this.
I faced the same problem here is code
Html code
<input type="file" name="costumePicUpload" id="costumePicUpload" onChange="viewImage(this)" >
<img src="#" id="imageThumb">
Javascript Function
function viewImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageThumb').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
When we choose the image file to upload it will read image using file reader and set it as a source for another image with id "imageThumb".
I tried to open file with
window.open("file:///D:/Hello.txt");
The browser does not allow opening a local file this way, probably for security reasons. I want to use the file's data in the client side. How can I read local file in JavaScript?
Here's an example using FileReader:
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
displayContents(contents);
};
reader.readAsText(file);
}
function displayContents(contents) {
var element = document.getElementById('file-content');
element.textContent = contents;
}
document.getElementById('file-input')
.addEventListener('change', readSingleFile, false);
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<pre id="file-content"></pre>
Specs
http://dev.w3.org/2006/webapi/FileAPI/
Browser compatibility
IE 10+
Firefox 3.6+
Chrome 13+
Safari 6.1+
http://caniuse.com/#feat=fileapi
The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.
I currently use this with development versions of Chrome (6.x). I don't know what other browsers support it.
Because I have no life and I want those 4 reputation points so I can show my love to (upvote answers by) people who are actually good at coding I've shared my adaptation of Paolo Moretti's code. Just use openFile(function to be executed with file contents as first parameter).
function dispFile(contents) {
document.getElementById('contents').innerHTML=contents
}
function clickElem(elem) {
// Thx user1601638 on Stack Overflow (6/6/2018 - https://stackoverflow.com/questions/13405129/javascript-create-and-save-file )
var eventMouse = document.createEvent("MouseEvents")
eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
elem.dispatchEvent(eventMouse)
}
function openFile(func) {
readFile = function(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
fileInput.func(contents)
document.body.removeChild(fileInput)
}
reader.readAsText(file)
}
fileInput = document.createElement("input")
fileInput.type='file'
fileInput.style.display='none'
fileInput.onchange=readFile
fileInput.func=func
document.body.appendChild(fileInput)
clickElem(fileInput)
}
Click the button then choose a file to see its contents displayed below.
<button onclick="openFile(dispFile)">Open a file</button>
<pre id="contents"></pre>
Try
function readFile(file) {
return new Promise((resolve, reject) => {
let fr = new FileReader();
fr.onload = x=> resolve(fr.result);
fr.readAsText(file);
})}
but user need to take action to choose file
function readFile(file) {
return new Promise((resolve, reject) => {
let fr = new FileReader();
fr.onload = x=> resolve(fr.result);
fr.readAsText(file);
})}
async function read(input) {
msg.innerText = await readFile(input.files[0]);
}
<input type="file" onchange="read(this)"/>
<h3>Content:</h3><pre id="msg"></pre>
Others here have given quite elaborate code for this. Perhaps more elaborate code was needed at that time, I don't know. Anyway, I upvoted one of them, but here is a very much simplified version that works the same:
function openFile() {
document.getElementById('inp').click();
}
function readFile(e) {
var file = e.target.files[0];
if (!file) return;
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('contents').innerHTML = e.target.result;
}
reader.readAsText(file)
}
Click the button then choose a file to see its contents displayed below.
<button onclick="openFile()">Open a file</button>
<input id="inp" type='file' style="visibility:hidden;" onchange="readFile(event)" />
<pre id="contents"></pre>
Consider reformatting your file into javascript.
Then you can simply load it using good old...
<script src="thefileIwantToLoad.js" defer></script>
Here is how to do it in typescript if Blob is good enough (no need to convert to ByteArray/String via FileReader for many use-cases)
function readFile({
fileInput,
}: {
fileInput: HTMLInputElement;
}): Promise<ArrayLike<Blob>> {
return new Promise((resolve, reject) => {
fileInput.addEventListener("change", () => {
resolve(fileInput.files);
});
});
}
here is how to do it in vanilla javascript
function readFile({
fileInput,
}) {
return new Promise((resolve, reject) => {
fileInput.addEventListener("change", () => {
resolve(fileInput.files);
});
});
}
It is not related to "security reasons" . And it does not matter if it local or file on network drive.
The solution for Windows OS could be IIS - Internet Information Services
and this is some details :
To open file in browser with Java Script window.open() , the file should be available on WEB server.
By creating Virtual Directory on your IIS that mapped to any physical drive you should be able to open files.
The virtual directory will have some http: address.
So instead of window.open("file:///D:/Hello.txt");
You will write window.open("http://iis-server/MY_VIRTUAL_DRIVE_D/Hello.txt");
The xmlhttp request method is not valid for the files on local disk because the browser security does not allow us to do so.But we can override the browser security by creating a shortcut->right click->properties In target "... browser location path.exe" append --allow-file-access-from-files.This is tested on chrome,however care should be taken that all browser windows should be closed and the code should be run from the browser opened via this shortcut.
You can't. New browsers like Firefox, Safari etc. block the 'file' protocol. It will only work on old browsers.
You'll have to upload the files you want.
Javascript cannot typically access local files in new browsers but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.
If you want to read the file abc.txt, you can write the code as:
var txt = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
txt = xmlhttp.responseText;
}
};
xmlhttp.open("GET","abc.txt",true);
xmlhttp.send();
Now txt contains the contents of the file abc.txt.