Hello how i can preview Image without upload to my server in asp.net C# and when i see the image i should press upload to upload to server.
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 Preview Image Before Upload It Takes Only One Step:- In preview() function we first create FileReader object to get the file data and then when the reader is loaded we create a function to get the output image and change its source to result and then we use readAsDataURL to preview the image.
Add a div element with a class named image-preview-container . Inside it, add another div element with a class named preview . This element will contain an img tag with an ID named preview-selected-image . This will be used to show the preview of the selected image.
In a HTML5 capable browser you can use the FileReader object to read a file from the users hdd as a base64 encoded string. You can use this base64 representation with css to show the preview. In older browsers you will need flash or similar plugin-based code to do it.
Here is a HTML5 example that works in all modern browsers:
<html>
<head>
<script>
var elmFileUpload = document.getElementById('file-upload');
function onFileUploadChange(e) {
var file = e.target.files[0];
var fr = new FileReader();
fr.onload = onFileReaderLoad;
fr.readAsDataURL(file);
}
function onFileReaderLoad(e) {
var bgStyle = "url('" +e.target.result + "')";
elmFileUpload.parentElement.style.background = bgStyle;
};
elmFileUpload.addEventListener('change',onFileUploadChange,false);
</script>
</head>
<body>
<input type="file" id="file-upload"/>
</body>
</html>
See a fiddle of it in action here
Yes it is possible.
Html
<input type="file" accept="image/*" onchange="showMyImage(this)" />
<br/>
<img id="thumbnil" style="width:20%; margin-top:10px;" src="" alt="image"/>
JS
function showMyImage(fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img=document.getElementById("thumbnil");
img.file = file;
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
}
You can get Live Demo from here.
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