How to preview selected image in input type=file in popup using jQuery?
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
Displaying picture before submitting the form JavaScript
The FileReader is async, which means you have to wait for the result to have been read.
you are missing:
pictureReader.onload = function () {
// code to set the image source
}
also you shouldn't remove the prefix (data:.+;base64
) in the beginning - that part is important
But i don't think you should be using the filereader to display base64 images. It's better & faster to use object url referring to the blob/file in it's binary form.
also, instead of using formdata, use formInputInHTML.files[0]
formInputInHTML.addEventListener("change", function () {
const formPicture = formInputInHTML.files[0];
const url = URL.createObjectURL(formPicture);
imagePlace.style.backgroundImage = `url(${url})`;
});
Show an image preview before upload
Here's a quick example that makes use of the URL.createObjectURL
to render a thumbnail by setting the src
attribute of an image tag to a object URL:
The html code:
<input accept="image/*" type="file" id="files" />
<img id="image" />
The JavaScript code:
document.getElementById('files').onchange = function () {
var src = URL.createObjectURL(this.files[0])
document.getElementById('image').src = src
}
The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:
function handleFileSelect (evt) {
// Loop through the FileList and render image files as thumbnails.
for (const file of evt.target.files) {
// Render thumbnail.
const span = document.createElement('span')
const src = URL.createObjectURL(file)
span.innerHTML =
`<img style="height: 75px; border: 1px solid #000; margin: 5px"` +
`src="${src}" title="${escape(file.name)}">`
document.getElementById('list').insertBefore(span, null)
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" accept="image/*" id="files" multiple />
<output id="list"></output>
Save and load an image from input
I was incorrect that server side is required. There is a good tutorial on codepen for exactly this codepen found from this blog
<div id="page-wrapper">
<h1>Image File Reader</h1>
<div>
Select an image file:
<input type="file" id="fileInput">
</div>
<div id="fileDisplayArea"></div>
CSS
html {
font-family: Helvetica, Arial, sans-serif;
font-size: 100%;
background: #333;
}
#page-wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
min-height: 300px;
border-top: 5px solid #69c773;
box-shadow: 0 2px 10px rgba(0,0,0,0.8);
}
h1 {
margin-top: 0;
}
img {
max-width: 100%;
}
#fileDisplayArea {
margin-top: 2em;
width: 100%;
overflow-x: auto;
}
Javascript:
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!"
}
});
}
Preview an image before it is uploaded
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>
Preview images before upload
Here is jQuery version for you. I think it more simplest thing.
$(function() { // Multiple images preview in browser var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) { var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) { var reader = new FileReader();
reader.onload = function(event) { $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview); }
reader.readAsDataURL(input.files[i]); } }
};
$('#gallery-photo-add').on('change', function() { imagesPreview(this, 'div.gallery'); });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add"><div class="gallery"></div>
html input file click event submit form before select file
If you want to submit the form as soon as the file is selected, use change event of that input.
<form action="formActionUrl" name="myForm">
<input type="file" name="myInput"/>
</form>
In Script
$(":file").change(function(e){
$("[name=myForm]").trigger('submit');
});
How to allow input type=file to accept only image files?
Use the accept attribute of the input tag. To accept only PNG's, JPEG's and GIF's you can use the following code:
<label>Your Image File
<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
</label>
Trying to preview image before uploading
export default function App() {
const [img, setImg] = useState(null);
const handleImg = (e) => {
setImg(URL.createObjectURL(e.target.files[0]));
}
return (
<div className="App">
<input type="file" onChange={handleImg} />
<img src={img}/>
</div>
);
}
Related Topics
Enabling Cross-Origin Resource Sharing on Iis7
Switch Statement for Greater-Than/Less-Than
Why Can't I Add Properties to a String Object in JavaScript
Using Settimeout on Promise Chain
Javascript: What Dangers Are in Extending Array.Prototype
What Does ':' (Colon) Do in JavaScript
Es6 Modules: Undefined Onclick Function After Import
How to Convert HTML to JSON Using PHP
How to Figure Out the Highest Z-Index in Your Document
How to Use Greasemonkey to Selectively Remove Content from a Website
How to Check If Geolocation Has Been Declined with JavaScript
How Send a Form with JavaScript When Input Name Is "Submit"
How to Auto-Scroll to End of Div When Data Is Added
Why Does Jquery Only Affect the First Div Element
Change <Select>'s Option and Trigger Events with JavaScript
Detect Rotation of Android Phone in the Browser with JavaScript