I am new to javascript and I am currently having problem with one of my projects which includes viewing of an image from the root folder of the website. Here is my current code:
var reader = new FileReader();
reader.onload = function(event){
var dataUri = event.target.result,
img = document.createElement("img");
img.src = dataUri;
document.body.appendChild(img);
};
reader.onerror = function(event){
console.log("File could not be read: " + event.target.error.code);
};
reader.readAsDataURL("/uploads/extras/item_a/image1.png");
That's my code and it doesnt show anything. And in my console it gives me an error or Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
Read files in JavaScript 1 The modern File System Access API #. The File System Access API provides an easy way to both read and write to files and directories on the user's local system. 2 Working with files, the classic way # 3 Select files #. ... 4 Read file metadata #. ... 5 Read a file's content #. ...
1. Show Image in Plain HTML Create a static image tag with an src attribute with an image URL in the HTML file. As you can see, I use the picsum website for demonstration purposes. It lets me get a random image URL with specific dimensions passed at the end of the URL. Pretty straight forward right?
When the file is loaded, the onload event triggers, the () => showImage(fr) captures the file reader fr reference, so that it can be passed as a parameter. showImage sets the source in the image tag, telling the browser to load the image.
You cannot read or write files in JS on client side (browsers). This can be done on serverside using the fs module in Node.js. It provides sync and async functions to read and write files on the file system. Let us look at the exmaples of reading and writing files using the fs module on node.js
Here's the correct way to do it
var openFile = function(file) {
var input = file.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('output');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
<input type='file' accept='image/*' onchange='openFile(event)'><br>
<img id='output' style="height:100px; width:100px;">
Do a little investigation to know where is the error in your code, that's better to learn
When you give it up, just leave a comment here, i'll be glad to help again! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With