I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image.
How can I do this?
First, we have a division element that contains the “img” tag. Using Jquery, we will change the “src” attribute of the “img” tag on upload to preview the image. The second element is the “input” tag. It is essential to specify type = “file” in this context.
To PREVIEW the image before uploading it to the SERVER from the Browser without using Ajax or any complicated functions. It needs an "onChange" event to load the image. IMPORTANT: If/when using this method it's necessary to remove the object URL to prevent memory leaks. This is done by calling URL.
The React app we are going to build has a file input. When you select an image with this file input, an image preview will show up below it. There is also a “Remove This Image” button that lets you remove the selected image and the preview as well.
Answer: Use the JS readAsDataURL() Method You can use the JavaScript readAsDataURL() method of the FileReader object to read the contents of the specified file. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. The FileReader result property returns the file's contents.
imgInp.onchange = evt => { const [file] = imgInp.files if (file) { blah.src = URL.createObjectURL(file) } }
<form runat="server"> <input accept="image/*" type='file' id="imgInp" /> <img id="blah" src="#" alt="your image" /> </form>
There are a couple ways you can do this. The most efficient way would be to use URL.createObjectURL() on the File from your <input>. Pass this URL to img.src to tell the browser to load the provided image.
Here's an example:
<input type="file" accept="image/*" onchange="loadFile(event)"> <img id="output"/> <script> var loadFile = function(event) { var output = document.getElementById('output'); output.src = URL.createObjectURL(event.target.files[0]); output.onload = function() { URL.revokeObjectURL(output.src) // free memory } }; </script>
You can also use FileReader.readAsDataURL() to parse the file from your <input>. This will create a string in memory containing a base64 representation of the image.
<input type="file" accept="image/*" onchange="loadFile(event)"> <img id="output"/> <script> var loadFile = function(event) { var reader = new FileReader(); reader.onload = function(){ var output = document.getElementById('output'); output.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; </script>
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