In my code, I am allowing the user to upload an image. Now I want to show this selected image as a preview in this same popup. How can I do it using jQuery?
The following is the input type I am using in my popup window.
HTML code:
<input type="file" name="uploadNewImage">
const chooseFile = document. getElementById("choose-file"); const imgPreview = document. getElementById("img-preview");
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.
To display a image selected from file input in React, we can call the URL. createObjectURL with the selected file object to and set the returned value as the value of the src prop of the img element. We define the img state which we use as the value of the src prop of the img element.
Demo
HTML:
<form id="form1" runat="server"> <input type='file' id="imgInp" /> <img id="blah" src="#" alt="your image" /> </form>
jQuery
function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#imgInp").change(function(){ readURL(this); });
Reference
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